簡體   English   中英

將二進制補碼輸出轉換為帶符號的十進制

[英]Converting two's complement output to signed decimal

如果這個問題已經回答,我很抱歉,但是我找不到我想要的東西。

我正在使用SPI設備進行c ++工作。 SPI器件以2的補碼形式輸出16位字的數據。 我試圖將此數據轉換為十進制以與過濾器一起使用。

我已經附上了一些示例代碼,要求用戶輸入二進制補碼的數字,然后輸出帶符號的十進制版本。

#include <iostream>     
#include <stdlib.h>
#include <cstdint>
#include <cmath>
#include <bitset>
using std::cout;
using std::endl;
using std::cin;
using std::hex;
using std::dec;
using std::bitset;
int main () {
    uint16_t x2=0;
    cout<<"Please enter the number you would like to convert from 2's complement.  "<<endl;
    cin>>x2;
    int diff=0x0000-x2;
    cout<<"The number you have entered is: "<<dec<<diff<<endl;
return 0;
}

當我運行該程序並輸入0x3B4A之類的內容時,它始終輸出0。我不確定是怎么回事,而且我對c ++還是很陌生,所以如果這是一個愚蠢的問題,請原諒。 另外,請忽略標題中的任何其他內容。 這是一個大型項目的一部分,我不記得標頭的哪些部分與這段特定的代碼一起使用。

謝謝!

編輯:這主要是本。 閱讀您最近的評論后,我進行了以下更改,但仍只是獲得與我輸入的十六進制數等效的十進制數

#include <iostream>     
#include <stdlib.h>
#include <cstdint>
#include <cmath>
#include <bitset>
using std::cout;
using std::endl;
using std::cin;
using std::hex;
using std::dec;
using std::bitset;
int main () {
    int16_t x2=0;
    cout<<"Please enter the number you would like to convert from 2's complement.  "<<endl;
    cin>>hex>>x2;
    int flags= (x2>>14) & 3;
    int16_t value=(x2 << 2) >> 2;
    cout<<"The number you have entered is: "<<dec<<value<<endl;
return 0;
}

我不確定OP的問題是否有必要,但是對於只想將16位2的補碼無符號整數轉換為有符號整數的公式的任何人,我認為它的變體看起來像這樣(對於輸入val ) :

(0x8000&val ? (int)(0x7FFF&val)-0x8000 : val)

總計:

  • 如果第一位為1,則它為負數,所有其他位為2的補碼
  • 通過減去0x8000提取負部分
  • 否則低位只是正整數值

將其包裝在函數中並執行一些基本的錯誤檢查(可能還可以強制輸入實際上是一個無符號的16位整數)可能是個好主意。

您要求cin讀取為十進制格式(不進行任何格式更改),因此,只要cin讀取不是0-9位數的x,它就會停止,並為您保留零。

只需在您的cin行中添加hexcin >> hex >> x2;

標准庫函數strtol將字符串輸入轉換為數字,並且只要您將0作為基數參數傳遞就支持0x前綴。

由於int16_t幾乎可以肯定是16位二進制補碼,因此可以使用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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