Saturday, April 24, 2021

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?

How can I declare an uint8_t array in Java

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

No comments:

Post a Comment