This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I'm getting two conflicting answers concerning the most significant bit: The Math Doctor Says: Check that against the decimal equivalent of 10110111 binary: 1 0 1 1 0 1 1 1 ^ ^ ^ ^ ^ ^ ^ ^ | | | | | | | |_________> 1 x 2^0 = 1 | | | | | | |___________> 1 x 2^1 = 2 | | | | | |_____________> 1 x 2^2 = 4 | | | | |_______________> 0 x 2^3 = 8 | | | |_________________> 1 x 2^4 = 16 | | |___________________> 1 x 2^5 = 32 | |_____________________> 0 x 2^6 = 64 |_______________________> 1 x 2^7 = 128
183 decimal However a JavaRanch user states: the most significant byte being 1 or (2 ^ 7)=-128 therefore shouldnt the answer be = -73 I dont see the math doctor taking the most significant digit into accout. Whos right? TIA
Hi, The difference between the two ( perfectly possible ) interpretations lie in if the number is signed or positive. If it's signed then the most significant bit is considered to be negative and with 8 data bits (one byte )we would get a range from - 128 to + 127. If the number is unsigned then the the range is from 0 to 255 inclusive. Hope that helps,
... The integral types are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively, and char, whose values are 16-bit unsigned integers representing Unicode characters. ...
Thus when dealing with byte, short, int, and long the number should be treated as signed which means the high-level bit is always the sign bit. When dealing with char the high-level bit is nothing, just another bit. HIH
I agree with the JavaRancher. The way I treat this: 1) a negative number is represented by inverting each bit of the corresponding positive number and then adding 1 (twos complement form) 2) consider the 7 right bits as the number and the 1 most left as the sign 10110111 - negative (remember!) so go back trough the statements above: *0110111 - just consider the 7 right bits *0110110 - minus 1 (the reversed way) *1001001 - invert and start counting: 64+0+0+8+0+0+1=73, get the sign back: -73 Erik Dark
Joined: Jan 28, 2002
I forgot to respond to the Math Doctor it doesn't treat bytes as being signed (I think).. GoodLuck ErikDark