Granny's Programming Pearls "inside of every large program is a small program struggling to get out" JavaRanch.com/granny.jsp

# bit values for bytes

sushil bhogale
Greenhorn
Posts: 8
byte = -42; It gets represented in bits as 1010 1010. How it gets represented as int i.e. in 32 bits ?

Henry Wong
author
Marshal
Posts: 21423
84
Originally posted by sushil bhogale:
byte = -42; It gets represented in bits as 1010 1010. How it gets represented as int i.e. in 32 bits ?

First of all, "-42" is not represented as "1010 1010". "1010 1010" is the representation of "-86". The representation of "-42" is "1101 0110".

To answer your question, to upcast a byte to an int, just sign extend the byte -- meaning the last bit is extended to the other bits. Hence, "1101 0110" becomes "1111 1111 1111 1111 1111 1111 1101 0110".

Henry

marc weber
Sheriff
Posts: 11343
How to represent -42 as bits:
• It's a negative value, so the process is...
• 42 in binary is 0010 1010.
• Inverting these bits gives 1101 0101.
• Then adding one gives 1101 0110.
• How to figure out what the byte 1010 1010 represents:
• The leading bit is 1, indicating a negative value, so the process is...
• Inverting these bits gives 0101 0101.
• And adding one gives 0101 0110.
• This is 86, so the original byte represents -86.
•