Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading