How do I convert a char
to an int
in C and C++?
相关问题
- Sorting 3 numbers without branching [closed]
- Multiple sockets for clients to connect to
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
For char or short to int, you just need to assign the value.
Same to int64.
All values will be 16.
char is just a 1 byte integer. There is nothing magic with the char type! Just as you can assign a short to an int, or an int to a long, you can assign a char to an int.
Yes, the name of the primitive data type happens to be "char", which insinuates that it should only contain characters. But in reality, "char" is just a poor name choise to confuse everyone who tries to learn the language. A better name for it is int8_t, and you can use that name instead, if your compiler follows the latest C standard.
Though of course you should use the char type when doing string handling, because the index of the classic ASCII table fits in 1 byte. You could however do string handling with regular ints as well, although there is no practical reason in the real world why you would ever want to do that. For example, the following code will work perfectly:
You have to realize that characters and strings are just numbers, like everything else in the computer. When you write 'a' in the source code, it is pre-processed into the number 97, which is an integer constant.
So if you write an expression like
this is actually equivalent to
which is then going through the C language integer promotions
and then truncated to a char to fit the result type
There's a lot of subtle things like this going on between the lines, where char is implicitly treated as an int.
Depends on what you want to do:
to read the value as an ascii code, you can write
to convert the character
'0' -> 0
,'1' -> 1
, etc, you can writeI have absolutely
null
skills in C, but for a simple parsing:...this worked for me:
I was having problems converting a char array like
"7c7c7d7d7d7d7c7c7c7d7d7d7d7c7c7c7c7c7c7d7d7c7c7c7c7d7c7d7d7d7c7c2e2e2e"
into its actual integer value that would be able to be represented by `7C' as one hexadecimal value. So, after cruising for help I created this, and thought it would be cool to share.This separates the char string into its right integers, and may be helpful to more people than just me ;)
Hope it helps!
Use
static_cast<int>
:Edit: You probably should try to avoid to use
(int)
check out Why use static_cast<int>(x) instead of (int)x? for more info.