Question

This question is a bit similar to my previous one, where I asked a "cross-language" way to write and read integers between a Java and a C# program. Problem was the endianess.

Anyway, I'm facing a secondary problem. My goal is now to store and retrieve an array of unsigned bytes (values from 0 to 255) in a way that it can be processed by both Java and C#.

In C# it's easy, since unsigned byte[] exists:

BinaryWriterBigEndian writer = new BinaryWriterBigEndian(fs);
// ...
writer.Write(byteData, 0, byteData.Length);

BinaryWriterBigEndian is... well... a big-endian binary writer ;)

This way, the file will contain a sequence composed by, for example, the following values (in a big-endian representation):

[0][120][50][250][221]...

Now it's time to do the same thing under Java. Since unsigned byte[] does not exist here, the array is stored in memory as a (signed) int[] in order to have the possibility to represent values higher than 127. How to write it as a sequence of unsigned byte values like C# does?

I tried with this:

ByteBuffer byteBuffer = ByteBuffer.allocate(4 * dataLength);
IntBuffer intBuffer = byteBuffer.asIntBuffer();
intBuffer.put(intData);
outputStream.write(byteBuffer.array());

Writing goes well, but C# is not able to read it in the proper way.

Was it helpful?

Solution

Since unsigned byte[] does not exist [...]

You don't care. Signed or unsigned, a byte is ultimately 8 bits. Just use a regular ByteBuffer and write your individual bytes in it.

In C# as well in Java, 1000 0000 (for instance) is exactly the same binary representation of a byte; the fact that in C# it can be treated as an unsigned value, and not in Java, is irrelevant as long as you don't do any arithmetic on the value.

When you need a readable representation of it and you'd like it to be unsigned, you can use (int) (theByte & 0xff) (you need the mask, otherwise casting will "carry" the sign bit).

Or, if you use Guava, you can use UnsignedBytes.toString().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top