简体   繁体   English

Arduino char数组为整数值

[英]Arduino char array to integer value

Stupid question here: 愚蠢的问题在这里:

I'm trying to convert a char array to a integer number. 我正在尝试将char数组转换为整数。 This is my case (extracted from main code, I've simplyfied it..): 这是我的情况(从主要代码中提取,我已经简单地确定了..):

int val;
char *buff;
uint8_t v1 = 2;
uint8_t v2 = 25;

buff[0] = v1;
buff[1] = v2;
val = strtol(buff, NULL, 16);

In that situation the val returns always '0' but, if I replace 'buff' with "0x225", it returns the expected value of 549. 在那种情况下,val始终返回“ 0”,但是,如果我将“ buff”替换为“ 0x225”,它将返回549的期望值。

What I'm doing wrong? 我做错了什么? Thanx in advance.. 提前感谢。

you need to learn C (C++ actually as arduino is programmed in C++). 您需要学习C(实际上是arduino是用C ++编程的C ++)。

strtol converts strings to numbers. strtol将字符串转换为数字。

string in C is a array of char elements ending with zero (not '0' but 0 ). C中的string是一个以零结尾的char元素数组(不是'0'而是0 )。 So "0x225" is the array of {'0', 'x', '2', '2', '5', 0} 因此,“ 0x225”是{'0', 'x', '2', '2', '5', 0}的数组

'2' is not the number 2 . '2'不是数字2 It is ASCII representation of char '2' which is 50 in decimal. 它是char'2'的ASCII表示形式,十进制为50。

buff[0] = '0';
buff[1] = 'x';
buff[2] = '2';
buff[3] = '2';
buff[4] = '5';
buff[5] = 0;

val = strtol(buff, NULL, 16);


buff[0] = 48;
buff[1] = 120;
buff[2] = 50;
buff[3] = 50;
buff[4] = 53;
buff[5] = 0;

val = strtol(buff, NULL, 16);

your code has many other issues. 您的代码还有许多其他问题。 You need to understand what 25 and what 0x25 is (they are not equal). 您需要了解25和0x25是什么(它们不相等)。 You should start from the book and PC compiler and learn language from the very basic stuff. 您应该从书本和PC编译器开始,并从最基础的知识中学习语言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM