I have a variable unsigned char that contains a value, 40 for example. I want a int variable to get that value. What's the simplest and most efficient way to do that? Thank you very much.
unsigned char is essentially a one byte of memory interpreted by the computer as an integer it is from 0 to 255.
We can convert char to int by negating '0' (zero) character. char datatype is represented as ascii values in c programming. Ascii values are integer values if we negate the '0' character then we get the ascii of that integer digit.
unsigned char is a character datatype where the variable consumes all the 8 bits of the memory and there is no sign bit (which is there in signed char). So it means that the range of unsigned char data type ranges from 0 to 255.
Beside the char type in C , there is also the unsigned char , and the signed char types . All three types are different , but they have the same size of 1 byte . The unsigned char type can only store nonnegative integer values , it has a minimum range between 0 and 127 , as defined by the C standard.
unsigned char c = 40;
int i = c;
Presumably there must be more to your question than that...
Try one of the followings, it works for me. If you need more specific cast, you can check Boost's lexical_cast and reinterpret_cast.
unsigned char c = 40;
int i = static_cast<int>(c);
std::cout << i << std::endl;
or:
unsigned char c = 40;
int i = (int)(c);
std::cout << i << std::endl;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With