【问题标题】:Decimal to binary conversion (8 bit) in CC中的十进制到二进制转换(8位)
【发布时间】:2019-07-18 05:09:46
【问题描述】:

我一直在做一个任务,到目前为止,这就是我得到的。

int n, c;

printf("Enter a decimal\n");
scanf_s("%d", &n);

printf("%d in binary is: ", n);

for (c = 7; c >= 0; c--)
{

    if (n >= 1)
        printf("1");
        n = n - 1;
    else (n < 1)
        printf("0");
        n = n / 2;
}

我是编码新手,正在努力找出从这里开始的地方。任何帮助将不胜感激。

【问题讨论】:

  • 有什么问题?好不好用?
  • 您要打印的第一个位是哪一位?这将告诉你如何开始你的 for 循环。
  • 是否缺少{ 大括号} 或缩进不佳?
  • 在此处发布编译器的错误消息以增加清晰度。

标签: c binary decimal


【解决方案1】:
void printbin(unsigned char val)
{
    for(unsigned char i = 0x80; i; i >>= 1)
        printf("%c", val & i ? '1' : '0');
    printf("\n");
}

【讨论】:

    【解决方案2】:

    使用位掩码测试是否设置了位。要构造位掩码,可以使用位移:

    1 << 0  // shift 1 0 bits to the left: 0b00000001
    1 << 1  // shift 1 0 bits to the left: 0b00000010
    1 << 2  // shift 1 0 bits to the left: 0b00000100
    1 << 3  // shift 1 0 bits to the left: 0b00001000
    1 << 4  // shift 1 0 bits to the left: 0b00010000
    1 << 5  // shift 1 0 bits to the left: 0b00100000
    1 << 6  // shift 1 0 bits to the left: 0b01000000
    1 << 7  // shift 1 0 bits to the left: 0b10000000
    

    然后您可以使用该值来测试是否使用按位与运算符设置了特定位:

    value & (1 << 4)  // evaluates to true if bit 5 is set.
                      // counted 1-based from the right.
    

    要使用它来输出 8 位值:

    char unsigned value = 42;  // an 8-bit value
    
    for (int bit = 8; bit; --bit) {  // count from 8 to 1
        putchar(value & (1 << (bit - 1)) ? '1' : '0');
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-24
      • 1970-01-01
      • 2017-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-22
      • 2019-04-09
      相关资源
      最近更新 更多