Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - byte array from string [duplicate]

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 } ?

like image 740
artem Avatar asked Jul 22 '26 19:07

artem


2 Answers

Loop through each pair of two characters and convert each pair individually:

byte[] bytes = new byte[str.length()/2];

for( int i = 0; i < str.length(); i+=2 )
    bytes[i/2] = ((byte)Character.digit(str.charAt(i),16))<<4)+(byte)Character.digit(str.charAt(i),16);

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.

like image 180
tskuzzy Avatar answered Jul 25 '26 08:07

tskuzzy


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)

like image 36
Charlie Avatar answered Jul 25 '26 09:07

Charlie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!