开发者

Assigning int to byte in java?

开发者 https://www.devze.com 2022-12-24 16:33 出处:网络
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 开发者_如何学Pythona byte for output. But
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 开发者_如何学Pythona byte for output. But in this case, a negative value is coming.

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


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


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

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 int in a byte, then byteVariable = (byte) intVariable does it. If you need to cast this back to int, you have to mask any possible sign extension (that is, intVariable = byteVariable & 0xFF;).


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.

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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号