|
JavaFAQ Home » General Java

How to avoid problems with signed bytes? Unsign them.
We know that Java has signed bytes, we know Java, some people do not, many programs are not aware about Java at all and send unsigned bytes to Java program which waits for signed ones... what happens with your program? Whom your chief is going to blame? Of cause not James Gosling - YOU 
Yesterday I was recommending to one newbie in Java the "Identifiers and primitive data types" lecture as a good start with Java data types. But suddenly he asked me about signed bytes and how he is supposed to deal with them - in many other languages they are not signed. If someone writes a Java program which communicates with non Java program and sends bytes, so what happens? Practical solution for Java signed bytes is below
Yes, maybe it is strange, maybe it is erratic, maybe it is bad. But it is just like this - Java has bytes, shorts, ints, and longs that are all signed.
-128...+127 - bytes range
the 8th bit which is (most significant) is used as a sign bit. 1 means 'negative', and 0 - 'positive'.
For example -128 is : 10000000
-125 is presented like so: 10000011 and so on.
Here is Java code example I use in my programs when I need to convert signed Java bytes into unsigned 'non Java' bytes. The code below changes range from -128... 127 to 0.... 255 and makes it possible to get "normal" integers
| Code: |
function getUnsignedBytes(){
byte[] bytes = getMyBytesFromSomewhere(); // here you get them here from some another place
int length = bytes.length;
for (int step = 0; step < length; step++){
int byteValue = new Integer(bytes[step]).intValue( );
if (byteValue < 0 ){
byteValue = bytes[step] & 0x80;
byteValue += bytes[step] & 0x7F;
}
}
return byteValue;
}
|
Printer Friendly Page
Send to a Friend
..
Search here again if you need more info!
|