Reputation: 1533
Hello i'm learning java programming and i just had task in my book which says to convert int varible to byte variable
byte b;
int i=257;
And when i convert int to b
b=(byte) i;
Output is 1 ? How it can be one when value of byte variable goes from -128 to 127 In my book they say byte variable have range of validity to 256 ?
Upvotes: 3
Views: 6234
Reputation: 1074276
The key here is to look at the bits.
int i = 257
gives us this set of bits (leaving off leading zeros):
b100000001
That value requires nine bits to hold (int
has 32, so plenty of room). When you do b = (byte)i
, it's a truncating cast. That means only what can be held by the byte (eight bits) is copied to it. So that gives us the lower eight bits:
b00000001
...which is the value 1
.
Upvotes: 2
Reputation: 10553
Because it can store any number from -128 to 127. A byte is always signed in Java. You may get its unsigned value by binary-anding it with 0xFF.
Example:
int i = 234;
byte b = (byte) i;
System.out.println(b); // -22
int i2 = b & 0xFF;
System.out.println(i2); // 234
Upvotes: 2
Reputation: 117587
257 == 00000000000000000000000100000001 (as integer which holds 32 bits)
1 == 00000001 (byte holds only 8 bits)
Upvotes: 6
Reputation: 27346
The range of 256
is because it can store any number from -128
all the way to 127
. The difference between these two numbers is 256
. The value of 1
has occurred thanks to overflow
, where you've attempted to store a value that can not be accurately represented with 7
bits and 1
sign bit.
Upvotes: 1
Reputation: 13844
its because byte range is from -128 to +127
Please check this link why byte is from -128 to 127
Upvotes: 0