将 int 转换为 GPIO 的字节

标签 c arrays raspberry-pi int converters

我正在尝试将 int 转换为 4 位数组,以便我可以使用 raspberry pi 的 GPIO 输出它们。我正在用 C 编程。我当前的功能是:

#include <stdio.h>

char *binaryToAbits(unsigned int answer, char *result) {
  if(answer>1)
  {
    result=binaryToAbits(answer-1,result);
  }
  *result='0'+(answer & 0x01);
  return result+1;
};

int main(void) {
  unsigned int numToConvert=2;
  char ascResult[]={0,0,0,0};
  int i;
  *binaryToAbits(numToConvert,ascResult)='\0';

  for(i=0;i<4;i++)
  {
    if(ascResult[i]!='1') ascResult[i]='0';
  }
  for(i=3;i>=0;i--)
  {
    printf("%c\n",ascResult[i]);
  }
  printf("\n");
  return 0;
}

问题是阵列的信号计算不正确。

最佳答案

使用递归使它变得比必要的更复杂。

你可以简单地做:

void binaryToAbits(unsigned int input, char *result)
{
    result[0] = (input & 0x1) ? '1' : '0';
    result[1] = (input & 0x2) ? '1' : '0';
    result[2] = (input & 0x4) ? '1' : '0';
    result[3] = (input & 0x8) ? '1' : '0';
}

关于将 int 转换为 GPIO 的字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45143314/

相关文章:

c++ - C/C++ 中的定宽 float

java - 如何使用 swig 将 wchar_t 数组转换为 java 的字节数组?

ios - Swift - 如何查找数组中数组中项目的索引

python - 树莓派 Omxplayer OpenCV

c - 为什么这个 pangram 程序不起作用?

c - Ubuntu C代码如何在另一个文件夹中执行命令

javascript - jQuery:将属性值转换为嵌套数组(字符串到数字)

python - 如果我不关闭 txt 文件会发生什么

c++ - 检查 Qt c++ 应用程序是否以 sudo 运行

c - Dev c++ 4.9.9.2 安装在我的 Windows 8.1 上。警告 : "Source file not compiled"