C++ 如何将 ASCII 字符转换为其 ASCII 整数值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15999272/
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-27 19:59:39  来源:igfitidea点击:

How to convert an ASCII char to its ASCII int value?

c++arduino

提问by user613326

I would like to convert a char to its ASCIIint value.

我想将 char 转换为其ASCIIint 值。

I could fill an array with all possible values and compare to that, but it doesn't seems right to me. I would like something like

我可以用所有可能的值填充一个数组并与之进行比较,但这对我来说似乎不对。我想要类似的东西

char mychar = "k"
public int ASCItranslate(char c)
return c   

ASCItranslate(k) // >> Should return 107 as that is the ASCII value of 'k'.

The point is atoi()won't work here as it is for readable numbers only.

重点是atoi()在这里不起作用,因为它仅适用于可读数字。

It won't do anything with spaces (ASCII 32).

它不会对空格(ASCII 32)做任何事情。

采纳答案by Waqar

Do this:-

做这个:-

char mychar = 'k';
//and then
int k = (int)mychar;

回答by John Zwinck

Just do this:

只需这样做:

int(k)

You're just converting the char to an int directly here, no need for a function call.

您只是在这里直接将 char 转换为 int,不需要函数调用。

回答by Hyman

A charis already a number. It doesn't require any conversion since the ASCII is just a mapping from numbers to character representation.

Achar已经是一个数字了。它不需要任何转换,因为 ASCII 只是从数字到字符表示的映射。

You could use it directly as a number if you wish, or cast it.

如果您愿意,您可以直接将其用作数字,或将其转换为数字。

回答by Tisys

In C++, you could also use static_cast<int>(k)to make the conversion explicit.

在 C++ 中,您还可以使用static_cast<int>(k)显式转换。

回答by Pete Becker

#include <iostream>

char mychar = 'k';
int ASCIItranslate(char ch) {
    return ch;
}

int main() {
    std::cout << ASCIItranslage(mychar);
    return 0;
}

That's your original code with the various syntax errors fixed. Assuming you're using a compiler that uses ASCII (which is pretty much every one these days), it works. Why do you think it's wrong?

这是修复了各种语法错误的原始代码。假设您使用的是使用 ASCII 的编译器(现在几乎每一种),它都可以工作。为什么你认为这是错误的?

回答by Linkon

To Convert from an ASCII characterto it's ASCII value:

要将ASCII 字符转换为它的ASCII 值

  char c='A';
    cout<<int(c);

To Convert from an ASCII Valueto it's ASCII Character:

要将ASCII 值转换为它的ASCII 字符

int a=67;
  cout<<char(a);