unsigned char to int in C++
94,991
Solution 1
unsigned char c = 40;
int i = c;
Presumably there must be more to your question than that...
Solution 2
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;
Solution 3
Google is a useful tool usually, but the answer is incredibly simple:
unsigned char a = 'A'
int b = a
Solution 4
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 */
Solution 5
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)
{
...
}
Author by
user1346664
Updated on February 17, 2020Comments
-
user1346664 over 4 years
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.
-
user1346664 about 12 yearsif I write printf("c: %x", c) I get 32. Then i write int i=c and when I print "i" I get 50!
-
Oliver Charlesworth about 12 years@user1346664:
%x
prints in hexadecimal. 32 hex is equal to 50 decimal. Use%d
instead. -
chris about 12 yearsWhy do you need an explicit cast for double->int? Won't it just truncate implicitly?
-
bytecode77 about 12 yearsYes it does, but you'll get a compiler warning, so it is recommended to do that.
-
chris about 12 yearsOdd, I don't get any warnings on the highest level of GCC.
-
Bo Persson about 12 yearsThe value of
a
(and ofi
) will be 40, as that is the value you just assigned. -
Bob Jarvis - Слава Україні about 11 yearsIf you ignore the compiler warning you'll discover that
i
gets the address where the string "40" is stored, which is of course what 'a' has in it. Ah - brings back to good ol' days before that wimpy ANSI standard thing - back when C was weakly typed, programmers had stronger minds, and Coca-Cola was made with real sugar! Bah! Kids these days..! Bah!! -
Aamir about 11 yearsThe question was about unsigned char. Why are you using a char*?
-
jaques-sam over 5 yearsPrefer C++ constructor style
int(c)
over C-cast style:(int)(c)