3

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 ?

Miljan Rakita
  • 1,211
  • 3
  • 16
  • 37

6 Answers6

6
257 == 00000000000000000000000100000001 (as integer which holds 32 bits)
  1 ==                         00000001 (byte holds only 8 bits)
Eng.Fouad
  • 107,075
  • 62
  • 298
  • 390
  • 1
    You can even test that in Java itself, if you preprend `0b` to the binary numbers. Ex: `System.out.println(1 == 0b00000001);` – afsantos Nov 06 '13 at 09:52
2

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
Linga
  • 9,691
  • 9
  • 45
  • 91
2

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.

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
1

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.

christopher
  • 24,892
  • 3
  • 50
  • 86
0

its because byte range is from -128 to +127

Please check this link why byte is from -128 to 127

Community
  • 1
  • 1
SpringLearner
  • 13,195
  • 20
  • 69
  • 111
0

-128 0 127, So range is 256.

-2^7 to 2^7-1
Masudul
  • 21,045
  • 5
  • 38
  • 51