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 ?

1
  • 3
    Which book are you reading? byte in Java is always signed. Commented Nov 6, 2013 at 9:46

6 Answers 6

6
257 == 00000000000000000000000100000001 (as integer which holds 32 bits)
  1 ==                         00000001 (byte holds only 8 bits)
Sign up to request clarification or add additional context in comments.

1 Comment

You can even test that in Java itself, if you preprend 0b to the binary numbers. Ex: System.out.println(1 == 0b00000001);
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

Comments

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.

Comments

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.

Comments

0

its because byte range is from -128 to +127

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

Comments

0

-128 0 127, So range is 256.

-2^7 to 2^7-1

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.