Jason
Jason

Reputation: 1309

Correctly convert decimal value to byte value

I need to convert decimal value like

int dec = 129;

into a byte value like

byte frame2 = (byte) 129;

but as you might already have guessed, it converts into an unexpected value. I want the byte value to be literally 129 instead of -127 (value of frame2).

How could you achieve it in Java? I would appreciate an explanation as well.

Thanks

Upvotes: 1

Views: 13033

Answers (2)

user207421
user207421

Reputation: 310840

I need to convert decimal value like

Stop right there. There is no such thing as a 'decimal value'. There are values, which are held in 2s-complement, and there are decimal representations.

int dec = 129;

That will be stored as 129(10), or 81(16).

into a byte value like

byte frame2 = (byte) 129;

The result of that will be -127, because bytes are signed in Java and your value sets the sign bit.

If you want to use the value as though it was 129, use (frame2 & 0xff). However it is quite likely that you don't need to do that at all.

Your question is actually about sign-extension of bytes in Java: it has nothing to do with decimals at all.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533442

You can't and most likely you don't need to. a byte is -128 to 127 by definition. However you can store any 256 different values in a byte if you want with encoding.

byte b = (byte) 129;
int i = b & 0xff; // == 129

or

byte b = (byte) (129 + Byte.MIN_VALUE);
int i = b - Byte.MIN_VALUE; // also 129.

Upvotes: 8

Related Questions