1

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
ernest_k
  • 44,416
  • 5
  • 53
  • 99

2 Answers2

1

It is happening because when you are shifting a, you are left with 1s 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 1s 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 1s on the front, here is a great explanation: Odd behavior when Java converts int to byte?

Sunil Dabburi
  • 1,442
  • 12
  • 18
  • This would be a better answer if you explained why the top bit is extended. – VGR Dec 22 '19 at 21:01
  • i work with images in processing and want to avoid using function [color()](https://processing.org/reference/color_datatype.html) because is too slow for my program. Every pixel from the image is an integer and in this integer is stored the `ARGB` information like this `AAAAAAAARRRRRRRRGGGGGGGGBBBBBBB` ,and in my program i need `R=G=B , A=255` – madalin costache Dec 22 '19 at 22:12
1

Try this. it is basically as left shift, and, and or operation.

byte a = (byte)240;
byte b = (byte)128;
byte c = 15;
int v = IntStream.of(0xFF, b, c, d).map(by-> by & 0xFF).reduce(0,
            (r, s) -> (r << 8) | s);

System.out.println(Integer.toBinaryString(v));
WJS
  • 36,363
  • 4
  • 24
  • 39