gpt4 book ai didi

C 将十进制 scanf 输入转换为二进制数组

转载 作者:行者123 更新时间:2023-11-30 15:25:43 26 4
gpt4 key购买 nike

我正在开发一个程序,让我的 RaspPi 驱动旧的 HP 十六进制显示器。我目前使用外壳/开关选项来控制 GPIO 输出选择。我想使用直接二进制输入。如何将十进制 scanf() 输入转换为二进制数组?

    #include <stdio.h>
#include <stdlib.h>
#include <wiringPi.h>


int main()
{

int displayNumber;

wiringPiSetup();

pinMode(0, OUTPUT);
pinMode(1, OUTPUT);
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(6, OUTPUT);

digitalWrite(0, LOW);
digitalWrite(1, LOW);
digitalWrite(2, LOW);
digitalWrite(3, LOW);
digitalWrite(6, LOW);

printf("Please select a number to display! 0-9\n");

scanf("%i", &displayNumber);


switch (displayNumber) {

case 0:
digitalWrite(6, LOW);
digitalWrite(3, LOW);
digitalWrite(0, LOW);
digitalWrite(1, LOW);
digitalWrite(2, LOW);
digitalWrite(6, HIGH);
break;

case 1:
digitalWrite(6, LOW);
digitalWrite(3, HIGH);
digitalWrite(0, LOW);
digitalWrite(1, LOW);
digitalWrite(2, LOW);
digitalWrite(6, HIGH);
break;

case 2:
digitalWrite(6, LOW);
digitalWrite(3, HIGH);
digitalWrite(0, LOW);
digitalWrite(1, LOW);
digitalWrite(2, LOW);
digitalWrite(6, HIGH);
// code
break;

case 3:
digitalWrite(6, LOW);
digitalWrite(3, HIGH);
digitalWrite(0, HIGH);
digitalWrite(1, LOW);
digitalWrite(2, LOW);
digitalWrite(6, HIGH);
// Code
break;

case 4:
digitalWrite(6, LOW);
digitalWrite(3, LOW);
digitalWrite(0, LOW);
digitalWrite(1, HIGH);
digitalWrite(2, LOW);
digitalWrite(6, HIGH);

break;

case 5:
digitalWrite(6, LOW);
digitalWrite(3, HIGH);
digitalWrite(0, LOW);
digitalWrite(1, HIGH);
digitalWrite(2, LOW);
digitalWrite(6, HIGH);

break;

case 6:
digitalWrite(6, LOW);
digitalWrite(3, LOW);
digitalWrite(0, HIGH);
digitalWrite(1, HIGH);
digitalWrite(2, LOW);
digitalWrite(6, HIGH);

break;
case 7:
digitalWrite(6, LOW);
digitalWrite(3, HIGH);
digitalWrite(0, HIGH);
digitalWrite(1, HIGH);
digitalWrite(2, LOW);
digitalWrite(6, HIGH);

break;
case 8:
digitalWrite(6, LOW);
digitalWrite(3, LOW);
digitalWrite(0, LOW);
digitalWrite(1, LOW);
digitalWrite(2, HIGH);
digitalWrite(6, HIGH);

break;
case 9:
digitalWrite(6, LOW);
digitalWrite(3, HIGH);
digitalWrite(0, LOW);
digitalWrite(1, LOW);
digitalWrite(2, HIGH);
digitalWrite(6, LOW);
break;
}



return 0;

}

最佳答案

将 switch 语句替换为

digitalWrite(6, LOW);
digitalWrite(3, displayNumber & 1 ? HIGH : LOW);
digitalWrite(0, displayNumber & 2 ? HIGH : LOW);
digitalWrite(1, displayNumber & 4 ? HIGH : LOW);
digitalWrite(2, displayNumber & 8 ? HIGH : LOW);
digitalWrite(6, HIGH);

关于C 将十进制 scanf 输入转换为二进制数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27732684/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com