0

Extending from converting an array of signed bytes to unsigned bytes, can this be performed more elegantly without the clunky for loop using Lambdas? So,

signed byte[] -> unsigned int[]

I note that there is no Arrays.stream(byte[]).

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
Paul Uszak
  • 377
  • 4
  • 18
  • Java has a [`Byte.toUnsignedInt`](https://docs.oracle.com/javase/8/docs/api/java/lang/Byte.html#toUnsignedInt-byte-). Honestly, I think `Stream` is a bit of overkill and a `for` loop is more elegant. – M. le Rutte May 20 '18 at 15:48

3 Answers3

0

Sure, you can:

int[] unsigned = IntStream.range(0, signed.length)
                          .map(i -> signed[i] & 0xFF)
                          .toArray();

where signed represents the array of bytes.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
0

Yes, you could achieve it using IntStream:

public static int[] toUnsignedIntArray(byte[] array) {
    return IntStream.range(0, array.length)
                    .map(idx -> array[idx] &  & 0xFF)
                    .toArray();
}

For more information, see this answer.

syntagma
  • 23,346
  • 16
  • 78
  • 134
0

You could do it like this.

int[] unsigned = IntStream.range(0, bytes.length)
                          .map(i -> 0x7F & bytes[i])
                          .toArray();
Bruno L
  • 839
  • 5
  • 9