簡體   English   中英

確定16位二進制數是負數還是正數

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM