Rochet2 Rochet2 - 2 months ago 11
Java Question

How can I reinterpret a byte as an integer in java?

I have a problem with conversions of different types.
In my code I am trying to use bytes and then convert them to an integer to be able to write x amount of bits from the integer to a storage of a kind.

The problem is that when I have a negative number as byte and I convert it to an integer, the bit representation as an integer has all the leading bits set as 1.
So when I try to save for example 10 bits from the integer, I get the leading bits as 1 instead of 0 as I expected.

Is there a way to reinterpret the byte as an integer while keeping the bit representation the same? I do not need to care about the actual numerical value of the integer.

From C++ I am used to having unsigned values which would prevent this issue, but now I am at loss with how to deal with this in java being limited to signed integers.

Example:

/*
decimal: -28
as byte: 11100100
as integer: 11111111111111111111111111100100
needed/expected integer: 00000000000000000000000011100100
*/
import java.util.*;
import java.lang.*;
import java.io.*;

class MyClass
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(Integer.toBinaryString((byte)-28));
}
}


https://ideone.com/VE960u

Answer
yourInt = yourByte & 255;

Just mask out the undesired bits.