Brian Bagnall wrote:
I'm writing some code that passes values from a Java program to a C++
program using an output stream. The C++ program requires a UBYTE, which is
an unsigned byte (values 0 to 255).
Java doesn't have unsigned bytes - only signed bytes (-127 to +127)
Right.
So if I want to pass a byte like 128 (0x80) to the C program, how do I do
it?
byte intToPseudoUnsignedByte(int n) {
if (n < 128) return n;
return n - 256;
}
Java objects to the following code:
byte val = 0x80;
byte val = intToPseudoUnsignedByte(128);
What happens is that Java uses 2's complement signed values. A negative
number n is represented as:
~(-n) + 1 (Reverse the sign back to positive, flip all bits, add 1)
(examples:)
So, -1 is in 2's complement is:
~(-(-1)1) + 1 = ~(00000001b) + 1 = 11111110b + 1 = 11111111b. That is
the bit pattern meaning 255 in unsigned. Try to stuff 255 into my
intToPseudoUnsignedByte function, and you get -1 --- which, again, has
the binary representation that you want for 255.
intToPseudoUnsignedByte(128) is -128. In 2's complement, that is
~(-(-128)) + 1 = 01111111b + 1 = 1000000, which is the bit pattern
meaning 128 in unsigned.
Hop this helped.
Soren.