Possible Duplicate:
Convert a string representation of a hex dump to a byte array using Java?
For example, I have a string "DEADBEEF". How can I convert it to byte[] bytes = { 0xDE, 0xAD, 0xBE, 0xEF } ?
For example, I have a string "DEADBEEF". How can I convert it to byte[] bytes = { 0xDE, 0xAD, 0xBE, 0xEF } ?
| |||
show 8 more comments
feedback
|
This question covers exactly the same content as earlier questions on this topic; its answers may be merged with another identical question. See the FAQ for guidance on how to improve it.
Loop through each pair of two characters and convert each pair individually:
I haven't tested this code out (I don't have a compiler with me atm) but I hope I got the idea through. The subtraction/addition simply converts 'A' into the number 10, 'B' into 11, etc. The bitshifting <<4 moves the first hex digit to the correct place. EDIT: After rethinking it a bit, I'm not sure if you're asking the correct question. Do you want to convert "DE" into {0xDE}, or perhaps into {0x44,0x45} ? The latter is more useful, the former is more like a homework problem type question. | |||||||||||||||
feedback
|
getBytes() would get you the bytes of the characters in the platform encoding. However it sounds like you want to convert a String containing a Hex representation of bytes into the actual represented byte array. In which case I would point you toward this existing question: Convert a string representation of a hex dump to a byte array using Java? (note: I personally prefer the 2nd answer to use commons-codec but more out of philosophical reasons) | |||
feedback
|
You can parse the string to a long and then extract the bytes:
| |||||
feedback
|
tskuzzy's answer might be right (didn't test) but if you can, I'd recommend using Commons Codec from Apache. It has a | |||
feedback
|
See the docs. Edit: for the dv'ers: I have apparently answered the wrong question. Nevertheless it is correct for the question title, so I am leaving as is. | |||||||||||||
feedback
|
{ 0xDE, 0xAD, 0xBE, 0xEF }
. – aroth Jun 28 '11 at 12:50