• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Converting into byte array !!

 
arun mahajan
Ranch Hand
Posts: 305
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
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];
b[0]=0xA1;
b[1]=0x01;
b[2]=0xFF;
b[3]=0x3A;
b[4]=0x2D;
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?
regards,
Arun
 
Marilyn de Queiroz
Sheriff
Posts: 9061
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
byte[] getBytes()
Convert this String into bytes according to the platform's default character encoding, storing the result into a new byte array. Reference
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic