c++type-conversionunsigned-integerunsigned-char

How to convert unsigned char to unsigned int in c++?


I have the following piece of code:

const unsigned char *a = (const unsigned char *) input_items;

input_items is basically the contents of a binary file.

Now a[0] = 7, and i want to convert this value to unsigned int. But when I do the following:

unsigned int b = (unsigned int) a[0];

and print both of these values, I get:

a[0] = 7
b = 55

Why does b not contain 7 as well? How do I get b = 7?


Solution

  • I think I see the problem now: You print the value of the character as a character:

    unsigned char a = '7';
    std::cout << a << '\n';
    

    That will print the character '7', with the ASCII value 55.

    If you want to get the corresponding integer value for the digit character, you can rely on that all digit characters must be consecutively encoded, starting with zero and ending with nine. Which means you can subtract '0' from any digit character to get its integer value:

    unsigned char a = '7';
    unsigned int b = a - '0';
    

    Now b will be equal to the integer value 7.