Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unsigned char to int in C++

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.

like image 200
user1346664 Avatar asked May 12 '12 12:05

user1346664


People also ask

Can an unsigned char be an integer?

unsigned char is essentially a one byte of memory interpreted by the computer as an integer it is from 0 to 255.

Can we convert char to int in C?

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.

What is the unsigned char in C?

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.

Does C have unsigned char?

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.


2 Answers

unsigned char c = 40;
int i = c;

Presumably there must be more to your question than that...

like image 114
Oliver Charlesworth Avatar answered Sep 24 '22 13:09

Oliver Charlesworth


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;
like image 45
Pierre23199223 Avatar answered Sep 23 '22 13:09

Pierre23199223