查找给定数字的等效二进制数

时间:2014-01-13 12:51:30

标签: c

Hello people ,   再次,尝试在C中创建一个程序,以帮助确定给定数字的等效二进制数是多少。我不知道该先做什么,我为它开发了一个简单的代码。但 问题 是我必须在其中进行一些即兴创作AS代码(READ BACKWARDS)。 所以关于这一点,代码并不是真的完整。这是我提出的代码..

#include <stdio.h>
void main()
{
int x,n;
printf("This program will help you find the equivalent binary-number to a given number \n");
printf("Enter number :");
scanf("%d",&n);
printf("The binary number to this number is(Read backwards) :");
for (;;n/=2)
    {
        x=n/2;
        if (x!=0) printf("%d",n%2);
        else {printf("%d\n",n%2); break;}
    }
}

现在 8 的等效二进制数是 1000 ,程序向后显示 0001 ,我完全不知道如何使它正确。 有什么想法吗?

3 个答案:

答案 0 :(得分:0)

使用右移>>运算符逐位读取数字。 然后n & 1测试该位是否设置。

  for (;n; n>>=1)
  {
    if (n & 1)
       printf("1");
    else
       printf("0");
  }
  puts("");

答案 1 :(得分:0)

易于理解的解决方案如下所示:

/* compile with gcc -Wall -Werror -o bprint bprint.c */

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

void
bprint (int64_t n)
{
  int bit;

  /* Handle negative numbers as positive ones, printing a - sign */
  if (n < 0)
    {
      n = -n;
      printf ("-");
    }

  /* Skip leading zeros. Comment this bit out if you want */
  for (bit = 63; (n <= ((1LL << bit) - 1)) && (bit > 0); bit--);

  for (; bit >= 0; bit--)
    printf ("%c", (n & (1LL << bit)) ? '1' : '0');

  printf ("\n");
}

int
main (char **argv, int argc)
{
  int j;
  for (j = 0; j < 100; j++)
    bprint (j);
  exit (0);
}

bprint函数中的第一个for循环跳过不需要的前导零位。第二个for循环执行打印。

请注意,这远非最有效的方法。更好的方法是注意int64_t通常需要一个最多66个八位字节的字符串(前导减去,64位,终止为零)。因此,可以将这些位逐个写入固定长度的字符数组,然后写入终止零,并使用printf%s打印结果。一个实用的函数要么采用文件句柄,FILE指针,要么返回一个字符串。这两个都留给读者练习;以上的目的是说明位操作是如何工作的。一旦您对运算符优先级有信心,也可以使用更少的括号。

答案 2 :(得分:0)

#include <stdio.h>
#include <limits.h>

int main(void){
    unsigned  n;
    size_t size = CHAR_BIT * sizeof(n);
    char bits[size + 1];
    char *p = &bits[size];
    *p = '\0';
    printf("This program will help you find the equivalent binary-number to a given number \n");
    printf("Enter number :");
    scanf("%u", &n);
    if(n){
        for (; n ; n >>= 1)
            *--p = (n & 1) ? '1' : '0';
    } else {
        *--p = '0';
    }
    printf("The binary number to this number is(Read backwards) :");
    printf("%s\n", p);
    return 0;
}