highflyer
highflyer

Reputation: 323

String array to Hex Array (Java)

I have a String array that actually consists of Hex characters.

Let's say the contents are ->

String array[] = {8C,D9,26,1D,69,B7,96,DB};  

Now I want these to be interpreted as Hex characters of 1 byte each and not as a String where each entry is 2 bytes.

StringBuilder output = new StringBuilder();
for (int j = 0; j < array.length; j++) {
        String temp = "\u00"+ array[j];
        output.append(temp);
    }

Tried something like that, but it's not possible because it keeps complaining about "illegal unicode escape". I tried using "\u00" (i.e. two backslashes before u, but stackoverflow displays only one there) instead of "\u00" to get around that error, but then I don't see the real Hex values in the array, instead I see a bunch of strings like -> "\U008C" , "\U00D9" and so on..

I want the after conversion values to be 0x8C, 0xD9, 0x26...

Thanks.

EDIT: I have updated the question, just to clarify there were no commas in the array itself. And eventually I need to put all those values together, and use that as a HMAC key that is a hex string and NOT a text string.

Upvotes: 4

Views: 10595

Answers (3)

Bohemian
Bohemian

Reputation: 425063

Let the JDK do the work for you:

String[] array = {"8C", "D9", "26", "1D", "69", "B7", "96", "DB"};

StringBuilder output = new StringBuilder();
for ( String hex : array ) {
    output.append( (char)Integer.parseInt( hex, 16 ) );
}

Basically just that one line inside the loop is all you need.

If you wanted your input to be just one big String (which would seem more convenient), just do this instead:

String input = "8CD9261D69B796DB";

StringBuilder output = new StringBuilder();
for ( String hex : input.replaceAll( "..(?!$)", "$0," ).split( "," ) ) {
    output.append( (char)Integer.parseInt( hex, 16 ) );
}

Edited:

If you want byte[] result, do this:

String[] array = {"8C", "D9", "26", "1D", "69", "B7", "96", "DB"};

byte[] bytes = new byte[array.length];
for ( int i = 0; i < array.length; i++ ) {
    bytes[i] = (byte)Integer.parseInt( array[i], 16 );
}

Upvotes: 4

Sujay
Sujay

Reputation: 6783

You can split it as follows:

public static void main(String[] args) {
    String givenString = "8C,D9,26,1D,69,B7,96,DB";
    String[] splitString = givenString.split("[,]");

    for(int index = 0; index < splitString.length; index++){
        System.out.print("0x"+ splitString[index]);
        System.out.print((index == splitString.length - 1) ? "":",");
    }
    System.out.println();

}

For joining them, well instead of my System.out statements, use StringBuilder or StringBuffer and append to it.

Upvotes: 0

Brad
Brad

Reputation: 9223

Use the String.split method to split on the ,

For each element in the returned array go data[i] = "0x" + data[i];

For each element in the array str += data[i]

EZ

Upvotes: 0

Related Questions