开发者

Java - byte array from string [duplicate]

开发者 https://www.devze.com 2023-03-15 18:06 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Convert a string representation of a hex dump to a byte array using Java?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Convert a string representation of a hex dump to a byte array using Java?

For e开发者_开发百科xample, I have a string "DEADBEEF". How can I convert it to byte[] bytes = { 0xDE, 0xAD, 0xBE, 0xEF } ?


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.


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)


You can parse the string to a long and then extract the bytes:

String s = "DEADBEEF";
long n = Long.decode( "0x" + s );  //note the use of auto(un)boxing here, for Java 1.4 or below, use Long.decode( "0x" + s ).longValue();
byte[] b = new byte[4];
b[0] = (byte)(n >> 24);
b[1] = (byte)(n >> 16);
b[2] = (byte)(n >> 8);
b[3] = (byte)n;


tskuzzy's answer might be right (didn't test) but if you can, I'd recommend using Commons Codec from Apache. It has a Hex class that does what you need.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号