如何在Java中将整数转换为字节? [英] How are integers cast to bytes in Java?

查看:208
本文介绍了如何在Java中将整数转换为字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Java不允许无符号类型,所以我想知道如何将一个整数转换为一个字节。说我有一个值为255的整数,我将整数转换为一个字节。是字节11111111中表示的值吗?换句话说,值是作为一个有符号的8位整数处理的,还是只是直接复制整数的最后8位?

I know Java doesn't allow unsigned types, so I was wondering how it casts an integer to a byte. Say I have an integer a with a value of 255 and I cast the integer to a byte. Is the value represented in the byte 11111111? In other words, is the value treated more as a signed 8 bit integer, or does it just directly copy the last 8 bits of the integer?

推荐答案

这称为缩小原始转换。根据规范:


将有符号整数转换为整数类型 T 最低位位,其中 n 是用于表示 T 类型的位数。除了可能丢失关于数值的大小的信息之外,这可能导致结果值的符号与输入值的符号不同。

A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.

所以这是你列出的第二个选项(直接复制最后8位)。

So it's the second option you listed (directly copying the last 8 bits).

我不确定你的问题,知道如何表示有符号整数值,所以为了安全,我将指出,字节值1111 1111在 two's complement system(Java使用)。

I am unsure from your question whether or not you are aware of how signed integral values are represented, so just to be safe I'll point out that the byte value 1111 1111 is equal to -1 in the two's complement system (which Java uses).

这篇关于如何在Java中将整数转换为字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆