Reputation: 197
I am having trouble understanding converting to and from bytes, or bytes in general
byte b = (byte)170;
System.out.println("Byte to int" + (int)b);
why is it that when I cast 170 to a byte then cast that byte to an int I get -86 and what is the proper way to do this?
EDIT: Okay so the answer to my question was really simple (byte
ranges from -128 to 127)...
Where I was getting confused is that I really want is binary 10101010 to be in the byte so I figured represent that number in int and put that in the byte. Can someone please tell me how I can get that binary number into a byte?
Upvotes: 2
Views: 3726
Reputation: 23793
The binary representation of 170 as a 32-bit integer is
0000 0000 0000 0000 0000 0000 1010 1010
When you cast that to a byte
, it becomes 1010 1010
. Since all integers in Java are signed, it sees 1010 1010
as a 2's complement 8-bit integer. That's -86.
When you convert this byte back to integer using (int) b
, it gets signed extended to:
1111 1111 1111 1111 1111 1111 1010 1010
Which is also -86. You want to apply a bit mask to it, so it becomes 170 again.
(int) (0xff & b)
will give you 170 back:
1111 1111 1111 1111 1111 1111 1010 1010
0000 0000 0000 0000 0000 0000 1111 1111 & (bitwise and)
---------------------------------------
0000 0000 0000 0000 0000 0000 1010 1010
Upvotes: 3
Reputation: 4233
To convert integer number into a byte:
int original = 170;
byte b = (byte)(0xFF & original);
This will put 10101010 into the byteNum by "cutting off" anything outside the first byte. If you print that number, you will get a -86. To convert back do this:
int num = (int)b & 0xFF;
This converts the byte into an integer, and then masks off the signature bit, restoring the value of 170.
Upvotes: 1
Reputation: 51030
The byte
primitive type has a minimum value of -128 and a maximum value of 127 (inclusive).
You are trying to assign 170 (int
) which is out of range of byte
by explicit casting, which results in the loss of information about the overall magnitude of a numeric value.
See here: Primitive Data Types
Also check this JLS section: 5.1.3 Narrowing Primitive Conversions
Upvotes: 1
Reputation: 36767
That's cause bytes are signed in java, so you're basically overflowing b.
Upvotes: 1
Reputation: 1268
Problem is that byte is 8-bit data type and its range is from -128 to 127. So there is no "losless conversion"...
Upvotes: 1