java - Int to Byte with same value -
i have , int , byte, need byte value same value int, answers have found end this:
int = 234; byte b = (byte) i; system.out.println(b); // -22 int i2 = b & 0xff; system.out.println(i2); // 234
now if int equaled 234, need byte value when printed out 234, not -22, understand why printed out -22 not need.
if knows how please me.
you can't. byte
can store numbers between -128
, 127
. when converting integer not representable, loss of information bound happen.
to elaborate, when converting int
byte
, lowest 8 bits considered. 234
representable in these 8 bits result negative number (-22
) because msb 1. in code, when do
int i2 = b & 0xff;
it renders number 32-bit integer bits except lowest 8 set zero. therefore, result same number 234
.
Comments
Post a Comment