Home > Net >  How to transform a array with several bytesinside into its translation in int?
How to transform a array with several bytesinside into its translation in int?

Time:10-29

Given an array fild with 4 bytes inside (R,G,B,A), i'm trying to translate this array full of 4 8bits numbers into its translation in 32bits.To be more clear, if i get an array such as :

byte[] tab = {1,2,3,4};

with translated in binary in 8bit :

1 = 0b00000001
2 = 0b00000010
3 = 0b00000011
4 = 0b00000100

Then, my method should return a byte array such as :

newTab = {00000001_00000010_00000011_00000100};

For some reasons, i'm trying to do this wihtout using a String to concatenate the bytes.

I've already tried something with binary operators such as <<, >> or |, but without succes...

so far, my code look like this :

byte[] tab = {1,2,3,4};
int tmp,tabToInt = 0;
for (int x = 0 ; x < tab.length ;   x){
tmp = tmp << (tab.length - 1 - x)*8;
byteToInt = byteToInt | tmp;
}
return tabToInt;

But it didn't seems to work, even less with negatives bytes... (like -1 = 0b11111111)

Thanks in advance for your answers !

CodePudding user response:

You can use ByteBuffer like this.

byte[] tab = {1, 2, 3, 4};
int tabToInt = ByteBuffer.wrap(tab).getInt();
System.out.println("decimal = "   tabToInt);
System.out.println("binary = "   Integer.toBinaryString(tabToInt));
System.out.println("hexadecimal ="   Integer.toHexString(tabToInt));

output

decimal = 16909060
binary = 1000000100000001100000100
hexadecimal =1020304

CodePudding user response:

ByteBuffer can do it, but only if you get passed at least 4 bytes.

The problem with your code is two-fold:

  • I think you typoed somewhere, your code doesn't even compile. I think you meant tmp = tab[x] << (tab.length - 1 - x)*8;. Your snippet never does anything with tab other than ask for its length.
  • Negative numbers extend, and java will convert any byte or short to an int the moment you do any math to it. So, 0b1111 1111, if you try to do e.g. << 8 on that, java first turns that -1 byte into a -1 int (so that's now 32 1 bits), and then dutifully left shifts it by 8, so now that's 24 1 bits, followed by 8 0 bits. You then bitwise OR that into your target, and thus now the target is mostly 1 bits. To convert a byte to an int without "sign extension", (b & 0xFF does it:
byte b = (byte) 0b1111_1111;
assert b == -1; // yup, it is
int c = b; // legal
assert c == -1; // yeah, still is. uhoh. That's...
int d = 0b11111111_11111111_11111111_11111111;
assert c == d; // yeah. We don't want that.
int e = (b & 0xFF);
assert e = 255;
int f = 0b0000000_0000000_0000000_11111111;
assert e == f; // yes!
  • Related