Hitesh Garg
Hitesh Garg

Reputation: 61

Convert Hexadecimal string to integer in android

I have a Bluetooth application which is receiving data in Hexa format in this format "01 0D 18 DA F1 10 03 41 0D 00"

convert this into the decimal and display in my app.

I am using this kind of logic.

int myInt = Integer.parseInt(data1,16);

but i want to convert particluar byte like in the above example. I want to decode only "03 41" into decimal and display . please help me out in this.

Upvotes: 0

Views: 746

Answers (3)

Toon Borgers
Toon Borgers

Reputation: 3658

What you could do is split the String with data1.split(" ") and then get the piece(s) you need. After that, just run those through the Integer.parseInt(input, 16) method and that should be it I think.

For reference, here's the javadoc on String.split()

Upvotes: 1

Kailash Dabhi
Kailash Dabhi

Reputation: 3513

It's simply too big for an int (which is 4 bytes and signed). The maximum value that a Java Integer can handle is 2147483657, or 2^31-1.
So You should use long and then cast it to int

Use

int myInt = (int)Long.parseLong(data1, 16);

hope this helps..!

Upvotes: 1

insomniac
insomniac

Reputation: 11756

What you need to do is split the Hexa string and store it in an array like

String[] array=Hex.split("\\s+"); //using space 

and then parse it like

int myInt = Integer.parseInt(array[1]+" "+array[2],16);

Upvotes: 1

Related Questions