c - 如何获取特定的数组元素

标签 c arrays

我已经声明了字符数组 char BCommand[100]="00LI002LE99" ,我只想使用 00299 .

这是我试过的代码:

 char Lcommand[3],Lecommand[3];
 unsigned char SlaveNodeID=0,NodeValue=0,ChSum2=0;
 Lcommand[0]=BCommand[4];
 Lcommand[1]=BCommand[5];
 Lcommand[2]=BCommand[6];
 Lecommand[0]=BCommand[9];
 Lecommand[1]=BCommand[10];
 SlaveNodeID = atoi(Lcommand);
 NodeValue = atoi(Lecommand);

有什么有效的方法吗?

最佳答案

我想你需要 int 值,如果你想要 00299 的整数值,你可以使用它。

int SlaveNodeID = (BCommand[4] - '0') * 100 + (BCommand[5]-'0') * 10 + (BCommand[6] - '0');
int NodeValue   = (BCommand[5] - '0') * 10  + (BCommand[6]-'0');  

printf("%3d",SlaveNodeID);
printf("%2d",NodeValue);

如果你想把它们变成字符串,然后声明大小为 4 和 3 的字符数组。使用 sprintf()snprintf() 而不是 printf ()

关于c - 如何获取特定的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19605824/

相关文章:

c - 什么是 Pic18 micro 最好的 c 编译器

c - 如何捕获退格键?

c - %i 或 %d 更喜欢哪一个

c - 在 C 中试验数组指针

java - 在构造函数中动态初始化数组 (Java)

c - 错误 : Redefinition of union

c - 为什么 fun(int i) 中的 printf 语句没有执行?

arrays - 在 Julia 中将 CartesianIndex 数组转换为 2D 矩阵

c++ - 给定 0 和 1 的二维数组,使用回溯找到其中的所有正方形

python - 使用 Numpy 计算相关系数