[英]Convert char to int in C and C++
How do I convert a char
to an int
in C and C++?如何在 C 和 C++ 中将
char
转换为int
?
Depends on what you want to do:取决于你想做什么:
to read the value as an ascii code, you can write要将值读取为 ascii 代码,您可以编写
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转换字符
'0' -> 0
, '1' -> 1
等,你可以写
char a = '4';
int ia = a - '0';
/* check here if ia is bounded by 0 and 9 */
Explanation :说明:
a - '0'
is equivalent to ((int)a) - ((int)'0')
, which means the ascii values of the characters are subtracted from each other. a - '0'
等价于((int)a) - ((int)'0')
,这意味着字符的 ascii 值相互减去。 Since 0
comes directly before 1
in the ascii table (and so on until 9
), the difference between the two gives the number that the character a
represents.由于
0
在 ascii 表中直接位于1
之前(依此类推,直到9
),两者之间的差异给出了字符a
代表的数字。
Well, in ASCII code, the numbers (digits) start from 48 .好吧,在 ASCII 码中,数字(数字)从48开始。 All you need to do is:
您需要做的就是:
int x = (int)character - 48;
Or, since the character '0' has the ASCII code of 48, you can just write:或者,因为字符'0'的 ASCII 码是 48,所以你可以写:
int x = character - '0'; // The (int) cast is not necessary.
C and C++ always promote types to at least int
. C 和 C++ 总是将类型提升到至少
int
。 Furthermore character literals are of type int
in C and char
in C++.此外,字符文字在 C 中是
int
类型,在 C++ 中是char
类型。
You can convert a char
type simply by assigning to an int
.您只需分配给
int
即可转换char
类型。
char c = 'a'; // narrowing on C
int a = c;
char is just a 1 byte integer. char 只是一个 1 字节的整数。 There is nothing magic with the char type!
char 类型没有什么神奇之处! Just as you can assign a short to an int, or an int to a long, you can assign a char to an int.
正如您可以将一个short 分配给一个int,或一个int 分配给一个long,您可以将一个char 分配给一个int。
Yes, the name of the primitive data type happens to be "char", which insinuates that it should only contain characters.是的,原始数据类型的名称恰好是“char”,暗示它应该只包含字符。 But in reality, "char" is just a poor name choice to confuse everyone who tries to learn the language.
但实际上,“char”只是一个糟糕的名称选择,让所有试图学习该语言的人感到困惑。 A better name for it is int8_t, and you can use that name instead, if your compiler follows the latest C standard.
更好的名称是 int8_t,如果您的编译器遵循最新的 C 标准,您可以使用该名称。
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.当然,在处理字符串时应该使用 char 类型,因为经典 ASCII 表的索引适合 1 个字节。 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:
例如,以下代码将完美运行:
int str[] = {'h', 'e', 'l', 'l', 'o', '\0' };
for(i=0; i<6; i++)
{
printf("%c", str[i]);
}
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.
当你在源代码中写'a'时,它被预处理成数字97,它是一个整数常量。
So if you write an expression like所以如果你写一个像这样的表达式
char ch = '5';
ch = ch - '0';
this is actually equivalent to这实际上相当于
char ch = (int)53;
ch = ch - (int)48;
which is then going through the C language integer promotions然后是通过 C 语言整数促销
ch = (int)ch - (int)48;
and then truncated to a char to fit the result type然后截断为 char 以适应结果类型
ch = (char)( (int)ch - (int)48 );
There's a lot of subtle things like this going on between the lines, where char is implicitly treated as an int.行之间有很多这样的微妙事情,其中 char 被隐式视为 int。
(This answer addresses the C++ side of things, but the sign extension problem exists in C too.) (这个答案解决了 C++ 方面的问题,但 C 中也存在符号扩展问题。)
Handling all three char
types ( signed
, unsigned
, and char
) is more delicate than it first appears.处理所有三种
char
类型( signed
、 unsigned
和char
)比它最初出现的要复杂得多。 Values in the range 0 to SCHAR_MAX
(which is 127 for an 8-bit char
) are easy: 0 到
SCHAR_MAX
(对于 8 位char
为 127)范围内的值很简单:
char c = somevalue;
signed char sc = c;
unsigned char uc = c;
int n = c;
But, when somevalue
is outside of that range, only going through unsigned char
gives you consistent results for the "same" char
values in all three types:但是,当
somevalue
超出该范围时,只有通过unsigned char
才能为所有三种类型的“相同” char
值提供一致的结果:
char c = somevalue;
signed char sc = c;
unsigned char uc = c;
// Might not be true: int(c) == int(sc) and int(c) == int(uc).
int nc = (unsigned char)c;
int nsc = (unsigned char)sc;
int nuc = (unsigned char)uc;
// Always true: nc == nsc and nc == nuc.
This is important when using functions from ctype.h , such as isupper
or toupper
, because of sign extension:这在使用ctype.h中的函数时很重要,例如
isupper
或toupper
,因为符号扩展:
char c = negative_char; // Assuming CHAR_MIN < 0.
int n = c;
bool b = isupper(n); // Undefined behavior.
Note the conversion through int is implicit;请注意,通过 int 进行的转换是隐式的; this has the same UB:
这具有相同的 UB:
char c = negative_char;
bool b = isupper(c);
To fix this, go through unsigned char
, which is easily done by wrapping ctype.h functions through safe_ctype :要解决这个问题,请通过
unsigned char
,这很容易通过通过safe_ctype包装ctype.h函数来完成:
template<int (&F)(int)>
int safe_ctype(unsigned char c) { return F(c); }
//...
char c = CHAR_MIN;
bool b = safe_ctype<isupper>(c); // No UB.
std::string s = "value that may contain negative chars; e.g. user input";
std::transform(s.begin(), s.end(), s.begin(), &safe_ctype<toupper>);
// Must wrap toupper to eliminate UB in this case, you can't cast
// to unsigned char because the function is called inside transform.
This works because any function taking any of the three char types can also take the other two char types.这是可行的,因为任何采用三种 char 类型中的任何一种的函数也可以采用其他两种 char 类型。 It leads to two functions which can handle any of the types:
它导致两个可以处理任何类型的函数:
int ord(char c) { return (unsigned char)c; }
char chr(int n) {
assert(0 <= n); // Or other error-/sanity-checking.
assert(n <= UCHAR_MAX);
return (unsigned char)n;
}
// Ord and chr are named to match similar functions in other languages
// and libraries.
ord(c)
always gives you a non-negative value – even when passed a negative char
or negative signed char
– and chr
takes any value ord
produces and gives back the exact same char
. ord(c)
总是给你一个非负值——即使传递一个负char
或负signed char
——并且chr
接受任何值ord
产生并返回完全相同的char
。
In practice, I would probably just cast through unsigned char
instead of using these, but they do succinctly wrap the cast, provide a convenient place to add error checking for int
-to- char
, and would be shorter and more clear when you need to use them several times in close proximity.在实践中,我可能只是通过
unsigned char
进行转换而不是使用这些,但它们确实简洁地包装了转换,提供了一个方便的地方来为int
-to- char
添加错误检查,并且当你需要时会更短更清晰近距离使用它们几次。
Use static_cast<int>
:使用
static_cast<int>
:
int num = static_cast<int>(letter); // if letter='a', num=97
Edit: You probably should try to avoid to use (int)
编辑:您可能应该尽量避免使用
(int)
int num = (int) letter;int num = (int) 字母;
check out Why use static_cast<int>(x) instead of (int)x?查看为什么使用 static_cast<int>(x) 而不是 (int)x? for more info.
了解更多信息。
I have absolutely null
skills in C, but for a simple parsing:我在 C 语言中拥有绝对
null
技能,但对于简单的解析:
char* something = "123456";
int number = parseInt(something);
...this worked for me: ...这对我有用:
int parseInt(char* chars)
{
int sum = 0;
int len = strlen(chars);
for (int x = 0; x < len; x++)
{
int n = chars[len - (x + 1)] - '0';
sum = sum + powInt(n, x);
}
return sum;
}
int powInt(int x, int y)
{
for (int i = 0; i < y; i++)
{
x *= 10;
}
return x;
}
It sort of depends on what you mean by "convert".这有点取决于您所说的“转换”是什么意思。
If you have a series of characters that represents an integer, like "123456", then there are two typical ways to do that in C: Use a special-purpose conversion like atoi() or strtol() , or the general-purpose sscanf() .如果您有一系列表示整数的字符,例如“123456”,那么在 C 中有两种典型的方法可以做到这一点:使用特殊用途的转换,如atoi()或strtol() ,或通用的sscanf () 。 C++ (which is really a different language masquerading as an upgrade) adds a third, stringstreams.
C++(它实际上是一种伪装成升级的不同语言)添加了第三个字符串流。
If you mean you want the exact bit pattern in one of your int
variables to be treated as a char
, that's easier.如果您的意思是希望将您的
int
变量之一中的确切位模式视为char
,那就更容易了。 In C the different integer types are really more of a state of mind than actual separate "types".在 C 中,不同的整数类型实际上更像是一种心态,而不是实际的单独“类型”。 Just start using it where
char
s are asked for, and you should be OK.只需在需要
char
的地方开始使用它,就可以了。 You might need an explicit conversion to make the compiler quit whining on occasion, but all that should do is drop any extra bits past 256.您可能需要显式转换以使编译器偶尔停止抱怨,但应该做的就是丢弃超过 256 的任何额外位。
Presumably you want this conversion for using functions from the C standard library.大概您希望这种转换用于使用 C 标准库中的函数。
In that case, do (C++ syntax)在这种情况下,做(C++ 语法)
typedef unsigned char UChar;
char myCppFunc( char c )
{
return char( someCFunc( UChar( c ) ) );
}
The expression UChar( c )
converts to unsigned char
in order to get rid of negative values, which, except for EOF, are not supported by the C functions.表达式
UChar( c )
转换为unsigned char
以消除负值,除 EOF 外,C 函数不支持负值。
Then the result of that expression is used as actual argument for an int
formal argument.然后将该表达式的结果用作
int
形式参数的实际参数。 Where you get automatic promotion to int
.您在哪里获得自动升级到
int
。 You can alternatively write that last step explicitly, like int( UChar( c ) )
, but personally I find that too verbose.您也可以明确地编写最后一步,例如
int( UChar( c ) )
,但我个人觉得这太冗长了。
Cheers & hth.,干杯&hth.,
I recomend to use the following function:我建议使用以下功能:
/* chartoint: convert char simbols to unsigned int*/
int chartoint(char s[])
{
int i, n;
n = 0;
for (i = 0; isdigit(s[i]); ++i){
n = 10 * n + (s[i] - '0');
}
return n;
}
The result of function could be checked by:函数的结果可以通过以下方式检查:
printf("char 00: %d \r\n", chartoint("00"));
printf("char 01: %d \r\n", chartoint("01"));
printf("char 255: %d \r\n", chartoint("255"));
For char or short to int, you just need to assign the value.对于 char 或 short to int,您只需分配值。
char ch = 16;
int in = ch;
Same to int64.与 int64 相同。
long long lo = ch;
All values will be 16.所有值都是 16。
Use "long long" instead a "int" so it works for bigger numbers.使用“long long”而不是“int”,因此它适用于更大的数字。 Here the elegant solution.
这是优雅的解决方案。
long long ChardToint(char *arr, size_t len){
int toptenf=1;
long long toptenLf=10000000LL;
long long makeintf=3000000000000;
makeintf= 0LL;
int holdNumberf=0;
for(int i=len-1;i>=0 ;i--){
switch(arr[i]){
case '0':
holdNumberf=0;
break;
case '1':
holdNumberf=1;
break;
case '2':
holdNumberf=2;
break;
case '3':
holdNumberf=3;
break;
case '4':
holdNumberf=4;
break;
case '5':
holdNumberf=5;
break;
case '6':
holdNumberf=6;
break;
case '7':
holdNumberf=7;
break;
case '8':
holdNumberf=8;
break;
case '9':
holdNumberf=9;
break;
default:
holdNumberf=0;
}
if(toptenf>=10000000){
makeintf=makeintf+holdNumberf*toptenLf;
toptenLf=toptenLf*10;
}else{
makeintf=makeintf+holdNumberf*toptenf;
toptenf=toptenf*10;
}
}
return makeintf;
}
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.我在将诸如
"7c7c7d7d7d7d7c7c7c7d7d7d7d7c7c7c7c7c7c7d7d7c7c7c7c7d7c7d7d7d7c7c2e2e2e"
类的字符数组转换为其实际整数值时遇到问题,该整数值可以用“7C”表示为一个十六进制值。 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 ;)这会将 char 字符串分隔成正确的整数,并且可能对更多的人有帮助,而不仅仅是我;)
unsigned int* char2int(char *a, int len)
{
int i,u;
unsigned int *val = malloc(len*sizeof(unsigned long));
for(i=0,u=0;i<len;i++){
if(i%2==0){
if(a[i] <= 57)
val[u] = (a[i]-50)<<4;
else
val[u] = (a[i]-55)<<4;
}
else{
if(a[i] <= 57)
val[u] += (a[i]-50);
else
val[u] += (a[i]-55);
u++;
}
}
return val;
}
Hope it helps!希望能帮助到你!
int charToint(char a){
char *p = &a;
int k = atoi(p);
return k;
}
You can use this atoi method for converting char to int.您可以使用此 atoi 方法将 char 转换为 int。 For more information, you can refer to this http://www.cplusplus.com/reference/cstdlib/atoi/ , http://www.cplusplus.com/reference/string/stoi/ .
更多信息可以参考这个http://www.cplusplus.com/reference/cstdlib/atoi/,http://www.cplusplus.com/reference/string/stoi/ 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.