在 C++ 中将无符号字符转换为 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10563642/
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
unsigned char to int in C++
提问by user1346664
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.
我有一个变量 unsigned char ,其中包含一个值,例如 40。我想要一个 int 变量来获取该值。最简单、最有效的方法是什么?非常感谢。
回答by Oliver Charlesworth
unsigned char c = 40;
int i = c;
Presumably there must be more to your question than that...
据推测,您的问题必须不止于此......
回答by Pierre23199223
Try one of the followings, it works for me. If you need more specific cast, you can check Boost's lexical_castand reinterpret_cast.
尝试以下方法之一,它对我有用。如果您需要更具体的演员表,您可以查看 Boost 的lexical_cast和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;
回答by Nurzhan Aitbayev
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 */
回答by bytecode77
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)
{
...
}
回答by NominSim
回答by user1030768
char *a="40";
int i= a;
The value in 'a' will be the ASCII value of 40 (won't be 40).
'a' 中的值将是 40 的 ASCII 值(不会是 40)。
Instead try using strtol() function defined in stdlib.h
而是尝试使用 stdlib.h 中定义的 strtol() 函数
Just be careful because this function is for string. It won't work for character
请小心,因为此函数用于字符串。它对角色不起作用