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?

1
  • is the "0x" in the beginning mandatory? Commented Jul 9, 2014 at 14:35

5 Answers 5

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)};
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.