0

I want to convert string to byte array like below:

If I have a string:

String str = "0x61";

I want it as:

byte[] byteArray = {0x61};

Any idea?

Alina
  • 130
  • 1
  • 13

5 Answers5

2

Are you leaving out parts of the information here? The problem you describe can be done with a simple

byte[] byteArray = {Byte.decode(str)};
Keppil
  • 45,603
  • 8
  • 97
  • 119
1

If I understand your question, then you could do -

String str = "0x61";
byte[] arr = new byte[] {(byte) Integer.parseInt(str.substring(2), 16)};
System.out.println(arr[0] == 0x61);

Output is

true
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

I don't really know what you are trying to achieve. Can you elaborate on your use case?

I believe what you want is

str.getBytes();

look here https://stackoverflow.com/a/18571348/2163130

Community
  • 1
  • 1
Marvin
  • 226
  • 1
  • 9
0

if your string doesn't have 0x before every digit, then this method will perform the conversion:

private byte[] generateByteArray(String byteArrayStr)
    {
        byte[] result = new byte[byteArrayStr.length() / 2];
        for (int i = 0; i < byteArrayStr.length(); i += 2)
        {       
            result[i / 2] = (byte)((Character.digit(byteArrayStr.charAt(i), 16) << 4) + Character.digit(byteArrayStr.charAt(i + 1), 16));               
        }

        return result;
    }

This method will transform "FF00" into {255, 0}

You will need to make sure that the length of the String is even, since every 2 digits will constitute 1 byte (in hex format).

Gil Moshayof
  • 16,633
  • 4
  • 47
  • 58
0

Step 1) Convert hex to long Step 2) Convert long to byte array.

String str = "0x61";    
long l = Long.valueOf(str).longValue(); //step 1
byte[] bytes = ByteBuffer.allocate(8).putLong(l).array(); //step 2
longofest
  • 616
  • 5
  • 16