using namespace std;
unsigned int num;
if (is >> hex >> num)
cout << num << '\n';
// Confusing name choice
char hex= "ABCD";
hex is also the name of a standard manipulator defined in <ios>. In the worst case you have a name collision and at best you have confusing results if you try to print num as hex:
// Prints "ABCD43981", not "abcd"
cout << hex << num << '\n';
Adding an explicit qualifier fixes the problem, but that's not an obvious fix without a bit of head scratching:
// Prints "abcd" as expected
cout << std::hex << num << '\n';
>How do I convert a char* or an unsigned char* to an unsigned int?
All of the above assumes char*. If you have an unsigned char* that's different because there's a distinct difference in type between unsigned char* and C strings. To use C string solutions with unsigned char* you have to somehow convert it to char* either by assignment to a temporary or by casting if you know it's a safe conversion.
I originally tried the stringstream thing similar to what you posted but it wouldn't work for me -- just proeuced some gigantic number. After a little more testing I find that the problem was becuse of my use of hex.
The whole reason a stringstream is used is to turn the hexadecimal number represented by the string "ABCD" into the integer number 43981. In other words, the character that each value (0x41, 0x42, etc...) represents is used instead of the actual value. If you want to get the actual values, don't do the conversion and just print the character cast to an int:
const char *p = "ABCD";
for (int i = 0; p[i] != '\0'; ++i)
std::cout << std::hex << int(p[i]) << '\n';