Hexadecimal to signed decimal
Aug 19, 2013 at 5:07pm UTC
HI,
How to convert a 12 bit hex string into a signed decimal.Is there a direct function to convert a hexadecimal in string to a signed decimal independent of system archi(32 bit or 64 bit), strtol is used but not for negative values.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#include <iostream>
#include <conio.h>
#include <sstream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
unsigned int x[3];
stringstream ss;
string A[3]={"ade" ,"0de" ,"fff" };
ss<<hex<<A<<endl;
for (int i=0;i<3;i++)
{
ss>>x[i];
cout<<x[i]<<" " <<static_cast <int >(x[i])<<endl;
}
_getch();
return 0;
}
I want the equivalent negative values of the string array.
Thanks in advance
Aug 19, 2013 at 5:30pm UTC
My personal favorite thing to use is std::string to do the job.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#include <cctype>
#include <iostream>
#include <string>
int hextoi(std::string hex)
{
int num = 0;
int pow16 = 1;
std::string alpha("0123456789ABCDEF" );
for (int i = hex.length() - 1; i >= 0; --i)
{
num += alpha.find(toupper(hex[i])) * pow16;
pow16 *= 16;
}
return num;
}
int main(int argc, char ** argv)
{
std::cout << hextoi("af1" ) << std::endl;
std::cout << hextoi("00f" ) << std::endl;
std::cout << hextoi("10A" ) << std::endl;
std::cout << hextoi("9D" ) << std::endl;
return 0;
}
Topic archived. No new replies allowed.