在java中将int分配给字节?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2529756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:53:14  来源:igfitidea点击:

Assigning int to byte in java?

java

提问by ramkumar

int val = 233;
byte b = (byte) val;
System.out.println(b);

I have a simple case: I have one integer with some value & I want to convert that value into a byte for output. But in this case, a negative value is coming.

我有一个简单的案例:我有一个带有某个值的整数,我想将该值转换为一个字节以进行输出。但在这种情况下,负值即将到来。

How can I successfully place the int value to byte type?

如何成功地将 int 值置于字节类型?

采纳答案by Darin Dimitrov

In Java byterange is -128 to 127. You cannot possibly store the integer 233 in a byte without overflowing.

在 Java 中,字节范围是 -128 到 127。您不可能在不溢出的情况下将整数 233 存储在一个字节中。

回答by polygenelubricants

Java's byteis a signed 8-bit numeric type whose range is -128to 127(JLS 4.2.1). 233is outside of this range; the same bit pattern represents -23instead.

Java的byte是一个符号的8位数字类型,其范围是-128127JLS 4.2.1)。233不在此范围内;-23取而代之的是相同的位模式。

11101001 = 1 + 8 + 32 + 64 + 128 = 233 (int)
           1 + 8 + 32 + 64 - 128 = -23 (byte)

That said, if you insist on storing the first 8 bits of an intin a byte, then byteVariable = (byte) intVariabledoes it. If you need to cast this back to int, you have to mask any possible sign extension (that is, intVariable = byteVariable & 0xFF;).

也就是说,如果您坚持将 an 的前 8 位存储int在一个字节中,那么byteVariable = (byte) intVariable就这样做。如果您需要将其转换回int,则必须屏蔽任何可能的符号扩展名(即intVariable = byteVariable & 0xFF;)。

回答by Ha.

If you need unsigned value of byte use b&0xFF.

如果您需要字节的无符号值,请使用b&0xFF.

回答by Peter Lawrey

You can use 256 values in a byte, the default range is -128 to 127, but it can represent any 256 values with some translation. In your case all you need do is follow the suggestion of masking the bits.

您可以在一个字节中使用 256 个值,默认范围是 -128 到 127,但它可以通过一些转换来表示任何 256 个值。在您的情况下,您需要做的就是遵循屏蔽位的建议。

int val =233; 
byte b = (byte)val; 
System.out.println(b & 0xFF); // prints 233.

回答by Ekesh Bahuguna

Since, byte is signed in nature hence it can store -128 to 127 range of values. After typecasting it is allowed to store values even greater than defined range but, cycling of defined range occurs as follows.cycling nature of range

因为,字节本质上是有符号的,因此它可以存储 -128 到 127 范围的值。类型转换后,允许存储甚至大于定义范围的值,但是,定义范围的循环发生如下。范围的循环性质