无法正确将十六进制转换为十进制

时间:2017-06-12 06:04:20

标签: c++ type-conversion hex decimal ascii

我无法理解十六进制字节。 当手册以十六进制表示标题为7Fh时,表示0111 1111对吗?根据在线十六进制转换器,其转换为十进制127。

string dataString;
//cout << dataString << endl;
//the output of dataString starts with "7F0304"

struct SENSOR_O
{
  fLeader fixedLeader;
  vLeader varLeader;
  vel     velocity;
  pos     position;
  bTrack  bottomTrack;
  bool error;
  std::string error_msg;
};

SENSOR_O datafields;
datafields = ParseData(dataString)

my class::SENSOR_O myclass::ParseData(const std::string &data)
{ 
const unsigned char *memblock;
ifstream::pos_type size;
ifstream test;
vector<double> dataSum;
int headerID = 125;
int startID = 0;

memblock = reinterpret_cast<const unsigned char *>(data.data());
cout << data[0] << data[1] << data[2] << data[3] << endl;

cout << "check value: "<< memblock[startID] << ", " << memblock[startID+1]<< endl;
cout << "double check value: " << double(memblock[startID]) << ", " << double(memblock[startID+1]) << endl;
cout << "7F should give me 127. Yes? Added total is: " << double(memblock[startID]) + double(memblock[startID+1]) << ends;

}

我看到的输出是

7F03
7, F
55, 70
7F should give me 127. Yes? Added total is: 125

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

理论上你是正确的,0x7F是b01111111,这是127.但是......

我假设memblock是char数组,然后你在这里做的是添加两个数字 - '7',其十进制值为55,'F'为70,得到正确的结果125 ..

假设您要将字符串十六进制表示转换为数字,您有多个选择,例如strtol,您也可以在hex string to int

查看此问题

编辑:好的,在你的情况下,可能像

string data = "7F03";
string toConvert = data.substr(0, 2);
int val = strtol(toConvert.c_str(), NULL, 16);