File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Converting into byte array !! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Converting into byte array !!" Watch "Converting into byte array !!" New topic

Converting into byte array !!

arun mahajan
Ranch Hand

Joined: Dec 07, 2001
Posts: 305
I have a HexString as below:
String xx = "A101FF3A2D";
now I want to convert this string into byte array. Perhaps if I can write something like:
byte[] b = new byte[xx.length()/2];
But I am confused how to write a program here as extracting 2 characters from the string xx and adding up 0x again make it string and I could not understand how to add this in byte array.
Though i have written following methods to achieve same but seems not satisfied and would like to know if there could be a better approach?
Marilyn de Queiroz

Joined: Jul 22, 2000
Posts: 9059
byte[] getBytes()
Convert this String into bytes according to the platform's default character encoding, storing the result into a new byte array. Reference

"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
No, getBytes() won't give the sort of answer Arun is looking for. As an example, consider the string "FF". The getBytes() method will most likely return a new byte[] {70, 70} - since 70 is the ASCII and Unicode value for the letter "F", and also the value in most popular character encoding systems I know of. Arun on the other hand is probably looking for a new byte[] {-1}, since "FF" as a hex code represents "11111111" in binary, which is either -1 or 255 bepending on your interpretation.
Arun - you're on the right track in general. It seems a bit silly to use a String for y, since you're just going to turn around and parse it as an int - why not use integer values in the first place? E.g. y = 10 rather than y = "10". And a switch staement will be more efficient than the long list of if / else if. There are also some math shortcuts you could use:

Also worth investigating is the method Integer.parseInt(String, int) - if you use 16 for the second argument, it parses base 16 strings. The only limit is that it onely returns an int, not an array of bytes. But of course you could use it to parse the individual bytes if you needed to.

"I'm not back." - Bill Harding, Twister
wood burning stoves
subject: Converting into byte array !!
jQuery in Action, 3rd edition