Home > Software design >  Convert byte array (signed bytes) to int array of corresponding unsigned bytes
Convert byte array (signed bytes) to int array of corresponding unsigned bytes

Time:11-13

Having given a command line parameter which is a hex string I use org.apache.commons.codec.binary.Hex.encodeHexString to get a byte[].

But of course Java bytes are signed. I'd like to treat this as a bunch of unsigned bytes (so where I have a byte value of, say, -128 I want it to be 0x80 = 128, or for -103 I want it to be 0x99 = 153.

It's not going to fit in a byte[] anymore, so let's make it a char[] (short[] would also work).

What is the way to do this in Java. I can write the obvious loop (or better: stream pipeline) but is there something better, built-in, e.g. some library method that I'm unaware of?

  • This isn't something java.nio.ByteBuffer does
  • java.nio.charset.CharsetDecoder has an API with the right signature but I don't know if there is (or how to get) an "identity" decoder.

(No work to show: internet searches turned up nothing like this.)

CodePudding user response:

I can write the obvious loop (or better: stream pipeline) but is there something better, built-in, e.g. some library method that I'm unaware of?

AFAIK, no.

There is no builtin "library method or something better" to do this. Just do it the clunky way. (FWIW, using a loop will most likely be more efficient than using streams.)

Better still, figure out a way to avoid doing it at all; e.g. keep the byte[] and use Byte.toUnsignedInt whenever you want to use the individual bytes in the array as unsigned.

CodePudding user response:

Try this.

byte[] byteArray = {0, 1, -128, -103};
int[] intArray = IntStream.range(0, byteArray.length)
    .map(i -> byteArray[i] & 0xff)
    .toArray();
System.out.println(Arrays.toString(intArray));

output:

[0, 1, 128, 153]
  • Related