"Unsigned" byte in Java
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Benedito_Santos
Posted On:   Tuesday, August 30, 2011 03:43 PM

I am reading byte b, where each bit has to be evaluated.
I am checking each bit with b & 0x80, b & 0x40, etc, until b & 0x01.

My problem happens with bytes larger than 0x80, which result in a weird negative number.

For instance, byte b = 0x80 (that is -128) results in an integer equal to -84. My byte, containing 0x80, results in a binary 1010 1100, not the expected 1000 0000.

Is there any way to get the correct bit configuration? My solution works for all cases, except when bit 0 is set.

Thanks for any help!

Re: "Unsigned" byte in Java

Posted By:   Anonymous  
Posted On:   Thursday, September 1, 2011 04:41 PM


package com.geekyarticles;

public class TestBits {

public static void main(String[] args) {
byte b=(byte)0x80;
System.out.println(b&0x80);
System.out.println(b&0x40);
System.out.println(b&0x20);
System.out.println(b&0x10);
System.out.println(b&0x08);
System.out.println(b&0x04);
System.out.println(b&0x02);
System.out.println(b&0x01);


}

}





produces the following output.




128
0
0
0
0
0
0
0





Can't see why you would have a different answer. Please let us see what you are doing.
--------------
http://www.geekyarticles.com
About | Sitemap | Contact