Reputation: 411
I am having trouble understanding Hexadecimal bytes. When a manual states Header ID in hex-ascii as 7Fh, that means 0111 1111 right? Which converts to 127 in decimal according to online hex-decimal converters.
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;
}
The output I see is
7F03
7, F
55, 70
7F should give me 127. Yes? Added total is: 125
What have I done wrong here?
Upvotes: 0
Views: 344
Reputation: 259
you are right in theory that 0x7F is b01111111 which is 127. But...
I am assume the memblock is char array and then what you are doing here is adding two numbers - '7' which has decimal value of 55 and 'F' which has 70 and get the correct result 125..
Assuming you want to convert string hex representation to number you have multiple choices, e.g. strtol, you can also check this question here hex string to int
EDIT: Ok in your case that can be something like
string data = "7F03";
string toConvert = data.substr(0, 2);
int val = strtol(toConvert.c_str(), NULL, 16);
Upvotes: 1