在 C 和 C++ 中将 char 转换为 int

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5029840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:13:36  来源:igfitidea点击:

Convert char to int in C and C++

c++cgcc

提问by mainajaved

How do I convert a charto an intin C and C++?

如何在 C 和 C++ 中将a 转换char为 an int

回答by Foo Bah

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. Since 0comes directly before 1in the ascii table (and so on until 9), the difference between the two gives the number that the character arepresents.

说明:
a - '0'等价于((int)a) - ((int)'0'),表示字符的 ascii 值相减。由于在 ascii 表中0直接出现在之前1(以此类推,直到9),因此两者之间的差异给出了字符所a代表的数字。

回答by Vlad Isoc

Well, in ASCII code, the numbers (digits) start from 48. All you need to do is:

好吧,在 ASCII 代码中,数字(数字)从48开始。您需要做的就是:

int x = (int)character - 48;

回答by Matt Joiner

C and C++ always promote types to at least int. Furthermore character literals are of type intin C and charin C++.

C 和 C++ 总是将类型提升到至少int. 此外,字符文字int在 C 和charC++中属于类型。

You can convert a chartype simply by assigning to an int.

您可以char简单地通过分配给一个类型来转换类型int

char c = 'a'; // narrowing on C
int a = c;

回答by Lundin

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.

char 只是一个 1 字节的整数。char 类型没有什么神奇之处!正如您可以将 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. 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.

是的,原始数据类型的名称恰好是“char”,这暗示它应该只包含字符。但实际上,“char”只是一个糟糕的名字选择,它会让每个试图学习这门语言的人感到困惑。更好的名称是 int8_t,如果您的编译器遵循最新的 C 标准,您可以改用该名称。

Though of course you shoulduse the char type when doing string handling, because the index of the classic ASCII table fits in 1 byte. You couldhowever 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:

当然,在进行字符串处理时您应该使用 char 类型,因为经典 ASCII 表的索引适合 1 个字节。然而,您也可以使用常规整数进行字符串处理,尽管在现实世界中没有实际原因为什么您会想要这样做。例如,以下代码将完美运行:

  int str[] = {'h', 'e', 'l', 'l', 'o', '
char ch = '5';
ch = ch - '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 = (int)53;
ch = ch - (int)48;

this is actually equivalent to

这实际上相当于

ch = (int)ch - (int)48;

which is then going through the C language integer promotions

然后通过 C 语言整数提升

ch = (char)( (int)ch - (int)48 );

and then truncated to a char to fit the result type

然后截断为字符以适合结果类型

char c = somevalue;
signed char sc = c;
unsigned char uc = c;
int n = c;

There's a lot of subtle things like this going on between the lines, where char is implicitly treated as an int.

两行之间有很多像这样的微妙事情,其中​​ char 被隐式​​视为 int。

回答by Fred Nurk

(This answer addresses the C++ side of things, but the sign extension problem exists in C too.)

(这个答案解决了 C++ 方面的问题,但 C 中也存在符号扩展问题。)

Handling all three chartypes (signed, unsigned, and char) is more delicate than it first appears. Values in the range 0 to SCHAR_MAX(which is 127 for an 8-bit char) are easy:

处理所有三种char类型(signedunsignedchar)比它最初出现的要复杂。0 到SCHAR_MAX127(对于 8 位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.

But, when somevalueis outside of that range, only going through unsigned chargives you consistent results for the "same" charvalues in all three types:

但是,当somevalue超出该范围时,只有通过unsigned char才能为char所有三种类型的“相同”值提供一致的结果:

char c = negative_char;  // Assuming CHAR_MIN < 0.
int n = c;
bool b = isupper(n);  // Undefined behavior.

This is important when using functions from ctype.h, such as isupperor toupper, because of sign extension:

由于符号扩展,这在使用ctype.h 中的函数时很重要,例如isupperor toupper

char c = negative_char;
bool b = isupper(c);

Note the conversion through int is implicit; this has the same UB:

注意通过 int 的转换是隐式的;这有相同的 UB:

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.

To fix this, go through unsigned char, which is easily done by wrapping ctype.hfunctions through safe_ctype:

要解决此问题,请通过unsigned char,这可以通过通过safe_ctype包装ctype.h函数轻松完成:

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.

This works because any function taking any of the three char types can also take the other two char types. It leads to two functions which can handle any of the types:

这是有效的,因为采用三种 char 类型中的任何一种的任何函数也可以采用其他两种 char 类型。它导致两个函数可以处理任何类型:

int num = static_cast<int>(letter); // if letter='a', num=97

ord(c)always gives you a non-negative value – even when passed a negative charor negative signed char– and chrtakes any value ordproduces and gives back the exact same char.

ord(c)总是给你一个非负值——即使传递了一个负值char或负值signed char——并且chr接受任何值ord产生并返回完全相同的char.

In practice, I would probably just cast through unsigned charinstead 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,并且当您需要多次使用它们时会更短更清晰近在咫尺。

回答by herohuyongtao

Use static_cast<int>:

使用static_cast<int>

char* something = "123456";

int number = parseInt(something);


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?for more info.

查看为什么使用 static_cast<int>(x) 而不是 (int)x?了解更多信息。

回答by T.E.D.

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(). C++ (which is really a different language masquerading as an upgrade) adds a third, stringstreams.

如果您有一系列表示整数的字符,例如“123456”,那么在 C 中有两种典型的方法可以做到这一点:使用专用转换,例如atoi()strtol(),或通用sscanf (). C++(实际上是一种伪装成升级的不同语言)添加了第三个字符串流。

If you mean you want the exact bit pattern in one of your intvariables to be treated as a char, that's easier. In C the different integer types are really more of a state of mind than actual separate "types". Just start using it where chars are asked for, and you should be OK. 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.

如果您的意思是希望将int变量之一中的确切位模式视为 a char,那会更容易。在 C 中,不同的整数类型实际上更像是一种精神状态,而不是实际单独的“类型”。只需在需要chars 的地方开始使用它,您应该就可以了。您可能需要进行显式转换以使编译器偶尔停止抱怨,但应该做的就是将任何额外的位删除到 256 之后。

回答by Henke

I have absolutely nullskills in C, but for a simple parsing:

null在 C方面绝对有技巧,但为了简单的解析:

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;
}

...this worked for me:

...这对我有用:

typedef unsigned char UChar;

char myCppFunc( char c )
{
    return char( someCFunc( UChar( c ) ) );
}

回答by Cheers and hth. - Alf

Presumably you want this conversion for using functions from the C standard library.

大概您希望这种转换是为了使用 C 标准库中的函数。

In that case, do (C++ syntax)

在这种情况下,执行(C++ 语法)

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;
}

The expression UChar( c )converts to unsigned charin 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 intformal argument. Where you get automatic promotion to int. You can alternatively write that last step explicitly, like int( UChar( c ) ), but personally I find that too verbose.

然后该表达式的结果用作int形式参数的实际参数。在哪里可以自动升级到int. 您也可以明确地编写最后一步,例如int( UChar( c ) ),但我个人觉得这太冗长了。

Cheers & hth.,

干杯 & hth.,

回答by Mathorlaz

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.

我在将类似 char 数组"7c7c7d7d7d7d7c7c7c7d7d7d7d7c7c7c7c7c7c7d7d7c7c7c7c7d7c7d7d7d7c7c2e2e2e"转换为其实际整数值时遇到问题,该值可以由“7C”表示为一个十六进制值。所以,在巡航寻求帮助后,我创建了这个,并认为分享会很酷。

This separates the char string into its right integers, and may be helpful to more people than just me ;)

这将字符字符串分成正确的整数,并且可能对不仅仅是我的更多人有帮助;)

##代码##

Hope it helps!

希望能帮助到你!