【发布时间】:2014-05-21 16:48:00
【问题描述】:
如果这个问题已经得到回答,但我无法找到我要找的东西,我深表歉意。
我正在使用 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;
}
【问题讨论】:
-
“转换”是解析的一部分。这个
0x0000-x2没有任何帮助。
标签: c++ decimal hex twos-complement