c++ convert 2 bytes of hex into integer -
i developing little embed app sends , responds chunk of data {80,09,1d,00,00} (all values in hexadecimal format) , being stored in vector<int>. have been looking method transforms bytes int type integer (c++). have been looking around cannot right answer, have code test results:
#include <iostream> #include<stdio.h> #include <vector> using namespace std; int main() { int x = 0x2008;//expected number result process vector<int> acmdresult; acmdresult.push_back(0x20); acmdresult.push_back(0x08); int aresult=0; aresult= (acmdresult.at(0)&0xff) | ( (acmdresult.at(1)>>8)&0xff) ; cout<<std::hex<<"conversion result: "<<aresult<<endl; /* 2 bytes of hex = 4 characters, plus null terminator */ x=0x0014;//expected number result process aresult=0; acmdresult.clear(); acmdresult.push_back(0x00); acmdresult.push_back(0x14); aresult= (acmdresult.at(0)&0xff) | ( (acmdresult.at(1)>>8)&0xff) ; cout<<std::hex<<"conversion result: "<<aresult<<endl; return 0; } the result first output is: 0 , in second is: 20 these not correct values! in advance
finally :
#include <iostream> #include<stdio.h> #include <vector> using namespace std; int main() { int x = 0x2008;//expected number result process vector<int> acmdresult; acmdresult.push_back(0x20); acmdresult.push_back(0x08); int aresult=0; aresult= ((acmdresult.at(0)&0xff)<<8) | ( (acmdresult.at(1))&0xff) ; cout<<std::hex<<"conversion result: "<<aresult<<endl; /* 2 bytes of hex = 4 characters, plus null terminator */ x=0x0014;//expected number result process aresult=0; acmdresult.clear(); acmdresult.push_back(0x00); acmdresult.push_back(0x14); aresult= (acmdresult.at(0)<<8&0xff) | ( (acmdresult.at(1))&0xff) ; cout<<std::hex<<"conversion result: "<<aresult<<endl; return 0; } what tryng , forth convertion array integer , , integer (i think using xor 2 bytes rigth side??)
Comments
Post a Comment