[英]Determining if a 16 bit binary number is negative or positive
我正在为温度传感器创建一个库,该库具有返回的16位二进制值。 我试图找到最好的方法来检查返回的值是负还是正。 我很好奇我是否可以检查最高有效位是1还是0,以及这是否是实现它的最佳方法以及如何成功实现它。
我知道我可以将其转换为十进制格式并进行检查,但是我只是好奇是否有更简单的方法。 我已经看到它是通过移动值来实现的,但是我并不完全了解该方法。 (我是C ++的新手)
float TMP117::readTempC(void)
{
int16_t digitalTemp; // Temperature stored in the TMP117 register
digitalTemp = readRegister(TEMP_RESULT); //Reads the temperature from the sensor
// Check if the value is a negative number
/*Insert code to check here*/
// Returns the digital temperature value multiplied by the resolution
// Resolution = .0078125
return digitalTemp*0.0078125;
}
我不确定如何检查代码是否有效,并且还无法编译并在设备上运行它,因为新的PCB设计和传感器尚未寄出。
我知道我可以将其转换为十进制并进行检查
我不确定你的意思。 整数是整数,它是一个算术对象,只需将其与零进行比较:
if( digitalTemp < 0 )
{
// negative
}
else
{
// positive
}
您可以按照您的建议测试MSB,但是并没有什么特别的好处,它缺乏清晰度,并且如果digitalTemp
的类型发生更改,它将被破坏或需要进行修改。
if( (digitalTemp & 0x8000 )
{
// negative
}
else
{
// positive
}
“转换为十进制”只能解释为转换为整数的十进制字符串表示形式 ,这不会使您的任务更简单,并且完全没有必要。
我不确定如何检查代码是否有效,并且还无法编译并在设备上运行它,因为新的PCB设计和传感器尚未寄出。
带有存根的测试工具可以在PC上编译并运行它,以实现与硬件相关的功能。 坦率地说,如果您是C ++的新手,那么在PC环境中实践基础知识可能会更好,无论如何,它们通常具有更好的调试功能和更快的开发/测试迭代。
一般来说
float TMP117::readTempC(void)
{
int16_t digitalTemp; // Temperature stored in the TMP117 register
digitalTemp = readRegister(TEMP_RESULT); //Reads the temperature from the sensor
// Check if the value is a negative number
if (digitalTemp < 0)
{
printf("Dang it is cold\n");
}
// Returns the digital temperature value multiplied by the resolution
// Resolution = .0078125
return digitalTemp*0.0078125;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.