• Post Reply Bookmark Topic Watch Topic
  • New Topic

Shifting a byte and getting negative answer!  RSS feed

 
H Melua
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello!

I'm trying to left shift a byte by 2... and I keep getting a negative byte!
This is the code I'm using


Can someone please tell me where i'm going wrong
I want it to print "1000"

Thanks
HannaH
[ November 11, 2007: Message edited by: H Melua ]
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all, parse and println works in decimal, so it will not treat what you have as binary nor will it print out as binary, in the way that you have it written. Anyway...

100 (decimal) ==> 0110 0100 (binary)

shift left by 2 ==> 1001 0000

this is a negative number due to the sign bit, we can take a twos complement to see what it is...

~x = 0110 1111
~x + 1 = -x = 0111 0000 = 112

hence, x = -112


Henry
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to parse the number as binary, use Byte.parseByte("00000100", 2).
When printing, use Integer.toBinaryString instead.

Also note that you can never get 1000 - you shift by two so you would get 10000.
 
H Melua
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you S O O O much guys...

(Rob, i was actually fighting with this method just now , and after horrible bruises i saw your "very much appreciated" post..) thanks again
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!