Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

bit values for bytes

 
sushil bhogale
Greenhorn
Posts: 8
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20836
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
  •  
    I agree. Here's the link: http://aspose.com/file-tools
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic