【问题标题】:Not getting proper value into int from byte value没有从字节值将正确的值转换为 int
【发布时间】:2016-10-22 07:38:07
【问题描述】:

我正在从蓝牙获取数据并希望将字节值转换为 int 并将结果显示为浮点数,因为我编写了以下代码

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);

从上面的代码我得到 prob1Tem = 65136.0 而不是 -400.0

谁能帮我解决这个问题

谢谢

【问题讨论】:

  • prob1Str = FE70 您称其为字节值。但实际上你有一个字符串,其中包含两个字节值的十六进制表示。

标签: java android


【解决方案1】:

只需将您的结果缩短!

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

int是32位,所以0x0000FE70 = 65136,是正值!

short 是 16 位,0xFE70 = -400,之后你将它重铸为 int 或 float。

查看that explanation了解更多详情。

【讨论】:

  • java.lang.NumberFormatException:值超出范围简称:“FE70”
  • float prob1Temp = (Short.parseShort(prob1b+prob1a,16)&0xffff);
  • 非常感谢 jbaptperez
【解决方案2】:
Integer.parseInt("FE70", 16) << 16 >> 16 

将正确扩展符号位。或同样不那么棘手且不受整数大小限制:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-27
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 2019-10-16
    相关资源
    最近更新 更多