3

I am stuck with these problem that how to convert a hex string to unsigned byte array or an Integer array..

Please look in this example.

String s= "1f5621ff8963545a12152250"; //this is my hex string

i want to convert this string to an int array

int buff[]={0x1f,0x56,0x21,0xff,0x89,0x63,0x54,0x5a,0x12,0x15,0x22,0x50};

how could i do that...

thanks for help..

1
  • 1
    What have you tried? In your example it seems one can just split s every 2 chars and add 0x in front of it. Commented Feb 29, 2012 at 12:46

2 Answers 2

4

One easy way: compute the length of your int array by dividing the length of the String by 2. Loop over the string, calling substring() to create the two-character strings "1f", "56", etc. Pass each string to Integer.parseInt(string, 16) (the second argument means that the argument is a hex string.) Store the results in the array as you compute them.

Sign up to request clarification or add additional context in comments.

2 Comments

if i do Integer.parseInt("1f", 16) it compiled as 31 ... not in 0x1f
There is only one way to store an int internally; the representation as decimal or hexadecimal (or octal or whatever) numerals only happens on output. If you want to print an int in hexadecimal, then you have to specifically use NumberFormat or printf() or simply Integer.toString(int, 16) to display it that way.
0

Iterate through the string and every two elements of the string create the integer like this:

0Xmm, where mm are the two elements you've just scanned.

Then you increase the index of your array and keep iterating through the string and adding to the current "top" place of the array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.