Joshua Beckford
Joshua Beckford

Reputation: 161

Byte/Int Conversion

So I am trying to take an int ex. 3240 and convert to a byte which prints -88.

        final int x = (int) (buffer[bufferIndex++] * 32767.0);
        System.out.println("1 " + x);
        byteBuffer[i] = (byte) x;
        System.out.println("2 " + (byte) x);
        System.out.println("3 " + (int) byteBuffer[i]);

I have problems converting back to a int from the byte. How do i take -88 and make it 3240 again?

Upvotes: 0

Views: 90

Answers (2)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279940

From the Java Language Specification regarding Narrowing Primitive Conversions

A narrowing primitive conversion may lose information about the overall magnitude of a numeric value and may also lose precision and range.

When you converted the int value 3240 to the byte value -88, you lost information in the truncated bytes. The int value 10920 would also have converted to -88. So would tons of other int values.

There's no way to get -88 back from 3240.

Upvotes: 3

SSC
SSC

Reputation: 3008

Other than Sotorios answer, this is what you can do for conversions:

byte to int

Byte b = new Byte(NUMBER);
int i = b.intValue();

int to byte

int i = NUMBER;
byte b = (byte) i;

Upvotes: 0

Related Questions