3

Basically, what I want is to convert a string like "123456" to unsigned byte array: [1, 226, 64]. However, I look everywhere and what I found is to get the 2's complements (signed) byte array [1, -30, 64]:

byte[] array = new BigInteger("123456").toByteArray();
System.out.println(Arrays.toString(array));

OUTPUT:

[1, -30, 64]

So, how can it be done in Java? I want the output to be:

[1, 226, 64]

EDIT: I know that byte can hold only up to 127, so instead of byte array I need it to be int array.

1
  • There is no unsigned byte type in Java, therefore you'll have to convert it into signed short/int array.
    – Crozin
    Mar 5, 2012 at 21:24

2 Answers 2

4

Java has no unsigned types, so you'll have to store the values in an int array.

byte[] array = new BigInteger("123456").toByteArray(); 
int[] unsigned_array = new int[array.length]; 
for (int i = 0; i < array.length; i++) { 
    unsigned_array[i] = array[i] >= 0 ? array[i] : array[i] + 256;
}

Fairly straightforward.

0
2

Java does not have unsigned bytes, so to convert them to ints as if they were unsigned, you need to AND them bitwise (&) with int 0xFF:

byte[] array = new BigInteger("123456").toByteArray();
for (int i = 0; i < array.length; i++) { 
    System.out.println(0xFF & array[i]);
}

Output:

1
226
64

You don't necessarily need to store them as an int array - it depends what you want to do with them...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.