lunes, 16 de agosto de 2010

Some thoughts about byte data types in Java and C#

We developed a simple communication application between JME and C# using sockets. We send some ASCII data from a C# to a java midlet, this data can contain printable ASCII (from 0 to 128) and non printable ASCII (from 129 to 255).

Everything was working smooth until we had to extract some bytes from the frame in the java midlet and compare them to non printable ASCII. Example:


byte x =byte[30]; //This position contains a non printable Happy Face ASCII

if(x == 254){
//This condition never is true
}


This happen because the java byte is signed, this means that this goes from -127 to 128, in the other hand c# byte is non-signed (from 0 to 255). Our first aproach was to convert all the byte arrays in java to short arrays adding 256 to negative ones, but thats not really necesary.

The rule is easy, it doesn't matter what operation you are doing over the signed byte, adding, substracting, multiplying, etc, always the result will be the same even if it is signed or unsigned. Why? The sign is in your mind! The sign is no more than an interpretation. But what happend when you want to compare this values or print them? In that case this will not work because casting a negative byte to char in java is not the same as deleting the sign.

Another example:


char x = (char)-1;

//x is not 255.


Whats the correct way to proceed?

Easy, you need to add, substract, multiply, etc signed or unsigned bytes? Don't worry do it, it will work always and even if this is signed or unsigned you will get exactly the same result. You need to compare the chars obtained? Delete the sign of the signed byte usign this line:


byte x = -1;
char y = (char)(x & 0xFF)


Sweet..

No hay comentarios:

Publicar un comentario