C++ dec2hex string function
#include <iostream> #include <sstream> #include <cstdio> using namespace std; string dec2hex(unsigned long long i); string dec2hex_c(unsigned int i); int main(int argc, char *argv[]) { int i1 = 255; int i2 = 2147483647;//2.14 billion unsigned long i3 = 4294967295UL;//4.29 billion unsigned long long i4 = 4300000000ULL;//4.3 billion >more than 32 bits cout << i1 << "," << dec2hex(i1)<< "," << dec2hex_c(i1) << endl; cout << i2 << "," << dec2hex(i2)<< "," << dec2hex_c(i2) << endl; cout << i3 << "," << dec2hex(i3)<< "," << dec2hex_c(i3) << endl; cout << i4 << "," << dec2hex(i4)<< "," << dec2hex_c(i4) << endl; return 0; } string dec2hex(unsigned long long i) { stringstream ss; ss << hex << uppercase << i; //ss << hex << lowercase << i; //ss << showbase << hex << lowercase << i; //prepends 0x //string s; ss >> s; return s; //alternate way to extract string return ss.str(); } string dec2hex_c(unsigned int i) //has limit of 32 bit integer { char s[20]; sprintf(s, "%X", i);//uppercase //sprintf(s, "%x", i);//lowercase return string(s); }
output:
255,FF,FF 2147483647,7FFFFFFF,7FFFFFFF 4294967295,FFFFFFFF,FFFFFFFF 4300000000,1004CCB00,4CCB00
code snippets are licensed under Creative Commons CC-By-SA 3.0 (unless otherwise specified)