Search code examples
javaarraysbyteunsigned

How to convert A string that represents an integer to unsigned byte array in Java?


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.


Solution

  • 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.