Hex
Jump to navigation
Jump to search
References
Many examples come from cplusplus.com and stackoverflow.com.
C / C ++
Read an integer from an hex string
Using atol
/* atol example */
#include <stdio.h>
#include <stdlib.h>
int main ()
{
long int li;
char szInput [256];
printf ("Enter a long number: ");
gets ( szInput );
li = atol (szInput);
printf ("The value entered is %d. The double is %d.\n",li,li*2);
return 0;
}
Using strtol, strtoll
strtol
(resp. strtoll
) returns LONG_MIN, LONG_MAX (resp. LLONG_MIN, LLONGMAX) in case of under/overflow.
/* strtol example */
#include <stdio.h>
#include <stdlib.h>
int main ()
{
char szNumbers[] = "2001 60c0c0 -1101110100110100100000 0x6fffff";
char * pEnd;
long int li1, li2, li3, li4;
li1 = strtol (szNumbers,&pEnd,10);
li2 = strtol (pEnd,&pEnd,16);
li3 = strtol (pEnd,&pEnd,2);
li4 = strtol (pEnd,NULL,0);
printf ("The decimal equivalents are: %ld, %ld, %ld and %ld.\n",
li1, li2, li3, li4);
return 0;
}
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
string s = "abcd";
char * p;
long n = strtol( s.c_str(), & p, 16 );
if ( * p != 0 ) {
cout << "not a number" << endl;
}
else {
cout << n << endl;
}
}
Using strtoul, strtoull
Use strtoul
(resp. strtoull
) when value to read is greater than numeric_limits<long>::max()
(resp. numeric_limits<long long>::max()
).
/* strtoul example */
#include <stdio.h>
#include <stdlib.h>
int main ()
{
char szInput [256];
unsigned long ul;
printf ("Enter an unsigned number: ");
fgets (szInput,256,stdin);
ul = strtoul (szInput,NULL,0);
printf ("Value entered: %lu. Its double: %lu\n",ul,ul*2);
return 0;
}
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
string s = "fffefffe";
char * p;
long n = strtoul( s.c_str(), & p, 16 );
if ( * p != 0 ) {
cout << "not a number" << endl;
} else {
cout << n << endl;
}
}
Using sscanf
#include <stdio.h>
main()
{
char s[] = "fffffffe";
int x;
sscanf(s, "%x", &x);
printf("%u\n", x);
}
Using stringstream
#include <sstream>
#include <iostream>
int main() {
unsigned int x;
std::stringstream ss;
ss << std::hex << "fffefffe";
ss >> x;
// output it as a signed type
std::cout << static_cast<int>(x) << std::endl;
}