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)
So if I want to pass a byte like 128 (0x80) to the C program, how do I do
it?
Java objects to the following code:
byte val = 0x80;
- Brian
Thomas Hawtin - 30 Jul 2006 12:55 GMT
> 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)
-128 to +127.
The sign is only important for performing arithmetic. Whether signed or
unsigned, it's still just eight bits.
> So if I want to pass a byte like 128 (0x80) to the C program, how do I do
> it?
out.write(128);
OutputStream.write(int) ignores the 24 high-order bits. If you want to
place the value into a byte array first, the equivalent value is -128.
So use -128, (byte)128, 128-0x100, or whatever.
Tom Hawtin
Patricia Shanahan - 30 Jul 2006 15:59 GMT
> 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
[quoted text clipped - 8 lines]
>
> byte val = 0x80;
0x80 is an int expression. There is an automatic conversion to byte when
an in-range int expression is used as a byte variable initializer. To
use an out-of-range expression, you need a cast:
public class ByteTest {
public static void main(String[] args) {
byte val = (byte)0x80;
System.out.println(Integer.toHexString(val & 0xff));
}
}
Patricia