简体   繁体   中英

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.

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;

Depends on what you want to do:

to read the value as an ascii code, you can write

char a = 'a';
int ia = (int)a; 
/* note that the int cast is not necessary -- int ia = a would suffice */

to convert the character '0' -> 0, '1' -> 1, etc, you can write

char a = '4';
int ia = a - '0';
/* check here if ia is bounded by 0 and 9 */

Actually, this is an implicit cast. That means that your value is automatically casted as it doesn't overflow or underflow.

This is an example:

unsigned char a = 'A';
doSomething(a); // Implicit cast

double b = 3.14;
doSomething((int)b); // Explicit cast neccesary!

void doSomething(int x)
{
...
}

Google is a useful tool usually, but the answer is incredibly simple:

unsigned char a = 'A'
int b = a
char *a="40";
int i= a;

The value in 'a' will be the ASCII value of 40 (won't be 40).

Instead try using strtol() function defined in stdlib.h

Just be careful because this function is for string. It won't work for character

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM