Parmar Subhash
Parmar Subhash

Reputation: 97

Not getting proper value into int from byte value

I am getting data from bluetooth and want to convert byte value to int and show result into float for that I have written following code

String prob1Str = manufactureData.substring(20, 24); // prob1Str = FE70

float prob1Temp =  (Integer.parseInt(prob1Str,16)&0xffff); // Here I am getting prob1Tem = 65136.0 instead of -400.0
model.setProb1Temp(prob1Temp);

From above code I am getting prob1Tem = 65136.0 instead of -400.0

can anybody help me how to resolve this

thanks

Upvotes: 0

Views: 98

Answers (2)

jbaptperez
jbaptperez

Reputation: 696

Just cast your result to short!

float prob1Temp = (short)Integer.parseInt(prob1Str, 16);

int is 32 bits, so 0x0000FE70 = 65136, it is a positive value!

Short is 16 bits, 0xFE70 = -400, you will recast it to int or float after.

Look at that explanation for more details.

Upvotes: 1

rustot
rustot

Reputation: 331

Integer.parseInt("FE70", 16) << 16 >> 16 

will correctly extend sign bit. or same less tricky and not bound to Integer size:

int i = Integer.parseInt("FE70", 16);
if (i >= 0x8000) i -= 0x10000;

Upvotes: 0

Related Questions