简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM