I need to do a conversion from 1 byte to integer using &
and |
. The output after conversion must be an integer with these bytes: (0xFF)(byte)(byte)(byte).
For example:
Input:
00000111
Output:
11111111000001110000011100000111
My code works if the byte is in range [0, 127]
int integer=7;
byte a=(byte)integer;
int b=(0xFF<<24)|(a<<16)|(a<<8)|(a);
System.out.println(Integer.toBinaryString(b));
If the byte is in range [-128, -1]
, it doesn't work
input:
10000000
Wrong output:
11111111111111111111111110000000
Expected output:
11111111100000001000000010000000
It is happening because when you are shifting a
, you are left with 1
s on the front.
For example:
a<<16
gives you 11111111100000000000000000000000
but you want 100000000000000000000000
a<<8
gives you 11111111111111111000000000000000
but you want 1000000000000000
So we need to mask those additional 1
s that are added on the front by doing & 0xFF
So replace this
int b=(0xFF<<24)|(a<<16)|(a<<8)|(a);
with this
int b = (0xFF<<24)|((a & 0xFF)<<16)|((a & 0xFF)<<8)|(a & 0xFF);
To know why we see 1
s on the front, here is a great explanation: Odd behavior when Java converts int to byte?