Hello,
In the below code, we have underflow or overflow?
Byte in java is 1 byte. It means the capacity of a byte is 0-255.
400 - 256 (0 to 127 and -1 to -127). I expected we have 144. But we have -112 in output.
Could you please explain it?
Thanks
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
Hello,
In the below code, we have underflow or overflow?
Byte in java is 1 byte. It means the capacity of a byte is 0-255.
400 - 256 (0 to 127 and -1 to -127). I expected we have 144. But we have -112 in output.
Could you please explain it?
Thanks
Use the Integer class's toHexString to see what the bits are for the value 400 = x190 or toBinaryString gives 1 1001 0000
The sign bit for the low order byte is 1 making it negative.
Casting it to a byte throws away the leading 1 leaving 1001 0000
Display the binary value of -112 gives 111111111111111111111111 1001 0000
If you don't understand my answer, don't ignore it, ask a question.
shervan360 (November 14th, 2019)
Thank you for your answer, but I didn't understand well.
Could you please more explain about it?
The sign bit for the low order byte is 1 making it negative.
Casting it to a byte throws away the leading 1s leaving 1001 0000
Display the binary value of -112 gives 111111111111111111111111 1001 0000
A byte has 8 bits. If this binary int value with these 32 bits (111111111111111111111111 1001 0000) is placed in a byte, the resulting 8 bits in the byte would be: 1001 0000.
The high order 24 bits would be truncated.
If you don't understand my answer, don't ignore it, ask a question.