Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I declare an uint8_t array in Java

I have a C++ Function in my DLL that needs an uint8_t array as an input Parameter, so the array looks something like that:

uint8_t input[input_length] = { 0x30, 0x41, 0x80, 0x8A...}; 

I want to use this function in Java with JNA, which means I have to creat an uint8_t array in Java. My first approach was to create an byte array like:

byte[] input = { 0x30, 0x41, 0x80, 0x8A...}; 

But then I realized that an uint8_t Variable in C++ has a range from 0..255, but a byte Variable in Java has an range from -128..127, and as you can see this array contains Values that are over 127 (like 0x8A), which means my Java declaration here is not valid. So my question is what type in Java is equivalent to uint8_t?

like image 947
conryyy Avatar asked Jan 30 '19 13:01

conryyy


People also ask

What is uint8_t in Java?

public class UInt8. Represents an 8-bit unsigned integer.

What is sizeof uint8_t?

sizeof(uint8_t *) is 8size of pointer. The size of the pointer depends on the target platform and it's usually 8 bytes on x64, 4 bytes on 32 bit machines, 2 bytes on some 16 bit microcontroller, etc.


2 Answers

Java doesn't have unsigned types. But it's not a big problem, since signed overflow in Java is defined as two's complement, you can just pass the byte to where JNA expects uint8_t. It's only a bit inconvenient to work with:

byte[] input = { 0x30, 0x41, (byte)0x80, (byte)0x8A...};

To read uint8_t back you'd do (x & 0xFF) to strip the sign extension and work with the result as an int.

like image 175
rustyx Avatar answered Oct 16 '22 10:10

rustyx


The value stored in a byte is a determinate one regardless how you interpret it, signed or unsigned that matters.

You can verify this easily with this code:

byte test = (byte)255;
System.out.println(test & 0xFF);

which outputs 255.

This means that once you created your byte[] with the values you need (and casting each value to byte allows you to set unsigned values). Then you are fine, on your JNI side you'll use:

jbyte* data = GetByteArrayElements(...)

and you'll be able to use it as an unsigned array of bytes by directly casting it if needed (uint8_t*)data.

like image 1
Jack Avatar answered Oct 16 '22 10:10

Jack