Unsigned char for int in C ++

I have an unsigned char variable that contains, for example, the value 40. I want the int variable to receive this value. What is the easiest and most effective way to do this? Thank you very much.

+4
source share
6 answers
unsigned char c = 40; int i = c; 

Presumably your question should be more than that ...

+12
source

Try one of the following: it works for me. If you require a more specific selection, you can check Boost 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; 
+4
source

Actually, this is an implicit cast. This means that your value is automatically cast as it does not overflow or end.

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) { ... } 
+2
source

Depends on what you want to do:

to read the value as 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 */ 
+2
source

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

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

The value in 'a' will be an ASCII value of 40 (not 40).

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

Just be careful, because this function is for the string. This will not work for the symbol.

-1
source

Source: https://habr.com/ru/post/1412143/


All Articles