Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# 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
Sheriff
Posts: 23275
125
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.
•