Parmar Subhash Parmar Subhash - 1 month ago 7
Android Question

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

Answer

Just cast your result to short!

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

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

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

Look at that explanation for more details.

Comments