Win a copy of Java Mock Exams (software) this week in the Programmer Certification (OCPJP) forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Byte.MIN_VALUE

 
Ramya Iyer
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone please explan why I am getting this output. I thouht Byte.MIN_VALUE should be - 2 to the power of 7 and hence its binary representation would be

2(power) 7 is represented as 10000000
complement 01111111
-2(power) 7 is 10000000

But this is not the represention in the output in line 3, and line 4 for hex

C:\>java test
Byte.MAX_VALUE in Binary:1111111
Byte.MAX_VALUE in Hex:7f
Byte.MIN_VALUE in Binary:11111111111111111111111110000000 //o/p line 3
Byte.MIN_VALUE in Hex:ffffff80 // o/p line 4

I have used Integer.toHexString function passing Byte.MAX_VALUE and Byte.MIN_VALUE, also used Integer.toBinaryString.

 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Integer methods toBinaryString and toHexString both take int as an argument. So when you pass a byte, it's automatically converted to a 32-bit int.
 
Henry Wong
author
Sheriff
Posts: 22610
111
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The toHexString() and toBinaryString() methods takes an int -- not a byte. The MIN_VALUE value has to be casted to an int first prior to calling the method. What you are seeing is the bit / hex pattern of the value after the cast has occurred.

BTW, this is true with MAX_VALUE too, but you don't see it because the cast conversion is simply a padding of lots of zeros.

Henry
 
Ramya Iyer
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Marc and Henry,

I understand that the value is getting converted into an int. In the first case for MAX_VALUE, we have zero's (sign bit) padded to the left and in the second case MIN_VALUE, we have sign bit padded to the left, which in this case is 1.
 
What are you doing? You are supposed to be reading this tiny ad!
the new thread boost feature brings a LOT of attention to your favorite threads
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!