0

I have a StringBuffer,strbuf=161656070200000000202020202001000000009E52;.

I want to convert into a byte array that looks like this:

byte[] byte_array=new byte[]
 {(byte)0x16,(byte)0x16,(byte)0x56,(byte)0x07,
  (byte)0x02,(byte)0x00,(byte)0x00,(byte)0x00,
  (byte)0x00,(byte)0x20,(byte)0x20,(byte)0x20,
  (byte)0x20,(byte)0x20,(byte)0x01,(byte)0x00,
  (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x9E,(byte)0x52};

Do I need to convert strbuf to hex string and then do getBytes()? What is the right approach to this problem?

3 Answers 3

8

You can try the following.

final String longHex = "161656070200000000202020202001000000009E52";
byte[] bytes = new BigInteger(longHex, 16).toByteArray();
System.out.println(Arrays.toString(bytes));

prints

[22, 22, 86, 7, 2, 0, 0, 0, 0, 32, 32, 32, 32, 32, 1, 0, 0, 0, 0, -98, 82]
Sign up to request clarification or add additional context in comments.

Comments

5

Let's break the problem down, and work backwards here.

Do you know:

  • How to convert an int into a byte (assuming the former is in range)?
  • How to convert a two-character String into an int?
  • How to convert a long String into chunks of two characters each?

I suspect that you are able to do any of these tasks individually. Simply doing all of them in sequence (in reverse order) will yield the solution you're looking for.

</teaching-to-fish>

3 Comments

instead of asking me what i know, i think it would be better if you explain us in your "systematic" way..
Perhaps. But merely giving you a chunk of code will let you copy-paste, move on, and then come back to SO next time you get stuck. Instead, leading you through the steps required to realise the solution on your own is more time-consuming, but means you can resolve similar problems yourself in future - which makes you a better developer.
i dont know what to say. Since i couldnt find a solution, i posted this question. And thank u very much..
0
String longHex = "....";
byte[] array = new byte[longHex.length() / 2];
for (int i=0; i<array.length; i++){
     Byte byte = Byte.parseByte(longHex.substring(i*2, i*2+2), 16);
     array[i] = byte;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.