1

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?

1
  • 4
    Please try to create a proper minimal reproducible example to show us. The code you show works with and without a cast (you don't need a cast, and any time you want to do a C-style cast like that you should take it as a sign you're doing something wrong). Commented Nov 26, 2021 at 11:19

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.