Hi
int i =132;
byte b =(byte)i;
System.out.println(b);
The o/p is -124
Why so ? I know this is very basic question, but still not able to map it how and what happens ?
Hi
int i =132;
byte b =(byte)i;
System.out.println(b);
The o/p is -124
Why so ? I know this is very basic question, but still not able to map it how and what happens ?
byte in Java is signed, so it has a range -2^7 to 2^7-1 - ie, -128 to 127. Since 132 is above 127, you end up wrapping around to 132-256=-124. That is, essentially 256 (2^8) is added or subtracted until it falls into range.
For more information, you may want to read up on two's complement.
132 is outside the range of a byte which is -128 to 127 (Byte.MIN_VALUE to Byte.MAX_VALUE) Instead the top bit of the 8-bit value is treated as the signed which indicates it is negative in this case. So the number is 132 - 256 = -124.
In java, an int is 32 bits. A byte is 8.
Everything in Java is signed, and bytes, ints, longs are encoded in two's complement.
In this number scheme the most significant bit specifies the sign of the number. If more bits are needed, the most significant bit is simply copied to the new msb.
So if you have byte 255: 11111111 and you want to represent it as an int (32 bits) you simply copy the 1 to the left 24 times.
Now, one way to read a negative two's complement number is to start with the least significant bit, move left until you find the first 1, then invert every bit afterwards. The resulting number is the positive version of that number
so: 11111111 goes to - 00000001 -> -1. This is what Java will display as the value.
What you probably want to do is know the unsigned value of the byte.
You can accomplish this with a bitmask that deletes everything but the least significant 8 bytes. (0xff)
So:
byte signedByte = -1;
int unsignedByte = signedByte & (0xff);
System.out.println("Signed: " + signedByte + " Unsigned: " + unsignedByte);
Would print out: "Signed: -1 Unsigned: 255"
Whats actually happening here?
We are using bitwise AND to mask all of the extraneous sign bits (the 1's to the left of the least significant 8 bits.)
1111111111111111111111111010101
&
0000000000000000000000001111111
=
0000000000000000000000001010101
Since the 32nd bit is now the sign bit instead of the 8th bit (And we set the sign bit to 0 which is positive), the original 8 bits from the byte are read by java as a positive value.
what actually happens is
java tries to convert the number in multiles of 256. eg. 132 it is near to first multiple of 256. so to make it 256 we are to add 124 in it so its output is -124.
lets suppose the number is 257. again it is near to 256. so to make it a multiple of 256 we have to subtract 1 from its answer will be -1.
again if the number is 700. to make it a multiple of 256 which is 768we will have to add 68 in it so its answer will be -68.
I hope it will help u out.