Converting String to Byte Array but keeping the same values

Viewed 205

What I'm trying to do is for example, lets say we had a string that looked like this:

String xyz = "1234567890";

How can I convert that String object into an Byte Array so the result byte array looks like:

[12, 34, 56, 78, 90];

I've tried various ways, from the very rudimentary xyz.getBytes() along with different encodings, which all just give some random values, albeit prob correct, just not what I'm looking for. Tried splitting up the string into an array, something like ["12", 34" ....] and trying to convert that into a byte array with no luck.

Am I not understanding here how strings are getting converted or is there some way of accomplishing this? Any tips appreciated. Thanks!

2 Answers
public static void main(String[] args) {
        String xyz = "1234567890";
        byte b[] = new byte[xyz.length() / 2];
        for (int i = 0; i < b.length; i++)
            b[i] = Byte.parseByte(xyz.substring(2 * i, 2 * i + 2));

        for (byte x : b) 
            System.out.println(x);
    }

->Use the substring method, notice that xyz.substring(0, 2) gives you the characters at index 0 and 1, not 2. The upper border is exclusive.

->Use parseByte

Do it as follows:

import java.math.BigInteger;
import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        // For decimal numbers
        String xyz = "1234567890";
        Byte[] arr = Arrays.stream(xyz.split("(?<=\\G..)")).map(Byte::parseByte).collect(Collectors.toList())
                .toArray(new Byte[0]);
        System.out.println(Arrays.toString(arr));

        // For haxadecimal numbers
        byte[] array = new BigInteger("A145BB5689", 16).toByteArray();
        System.out.println(Arrays.toString(array));
    }
}

Output:

[12, 34, 56, 78, 90]
[0, -95, 69, -69, 86, -119]

Note: The regex (?<=\G..) matches an empty string that has the last match (\G) followed by two characters (..) before it ((?<= )).

Related