string Arduino:字符串到 int 得到奇怪的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10671810/
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
Arduino: String to int gets strange values
提问by cstrutton
I want to convert a String
to an int
, and all I could find is that you have to convert the String to a char array and then cast this array to an int
, but my code produces strange values and I can't figure out what the problem is.
我想将 a 转换String
为 an int
,我能找到的只是您必须将 String 转换为 char 数组,然后将此数组转换为 an int
,但是我的代码产生了奇怪的值,我无法弄清楚问题是什么.
void ledDimm(String command)
{
// Get the Value xx from string LEDDimm=xx
String substring = command.substring(8, command.length());
Serial.println("SubString:");
Serial.println(substring);
Serial.println("SubString Length:");
Serial.println(substring.length());
// Create a Char Array to Store the Substring for conversion
char valueArray[substring.length() + 1];
Serial.println("sizeof ValueArray");
Serial.println(sizeof(valueArray));
// Copy the substring into the array
substring.toCharArray(valueArray, sizeof(valueArray));
Serial.println("valueArray:");
Serial.println(valueArray);
// Convert char array to an int value
int value = int(valueArray);
Serial.println("Integer Value:");
Serial.println(value);
// Write the Value to the LEDPin
analogWrite(LEDPin, value);
}
And the serial output looks like this:
串行输出如下所示:
Received packet of size 11
From 192.168.1.4, port 58615
Contents:
LEDDimm=100
SubString:
100
SubString Length:
3
sizeof ValueArray
4
valueArray:
100
Integer Value:
2225
I expected to get an int with the value of 100 but the actual int is 2225?! What have I done wrong here?
我希望得到一个值为 100 的 int 但实际的 int 是 2225?!我在这里做错了什么?
回答by Bachi
There is even an (undocumented) toInt()
method in the String class:
toInt()
在 String 类中甚至有一个(未记录的)方法:
int myInt = myString.toInt();
int myInt = myString.toInt();
回答by cstrutton
You need to use the function int value = atoi(valueArray);
where valueArray
is a null terminated string.
您需要使用函数int value = atoi(valueArray);
wherevalueArray
是一个空终止字符串。
回答by Santhosh Ravichandran
The toInt () method is very useful in this aspect, but I found that it is able to convert only strings of length five or less, especially a value less than 65535 as its the maximum value int can take. Over this value, it just gives random numbers (overflowing values). Please be aware of this when you use this method as it killed a lot of my useful time to figure this out. Hope it helps.
toInt() 方法在这方面非常有用,但我发现它只能转换长度为 5 或更小的字符串,尤其是小于 65535 的值,因为它的最大值 int 可以取。在这个值上,它只给出随机数(溢出值)。当您使用此方法时请注意这一点,因为它浪费了我很多有用的时间来解决这个问题。希望能帮助到你。