1

如何将无符号整数表示为 Binary ?

4

2 回答 2

2

要创建某个整数值的字符串表示,您可以使用以下代码

#include <stdlib.h>

int main(int argc, char *argv[]) {
  int j;
  unsigned int value = 1024+2048+4096; // some value
  char mask[8*sizeof(unsigned int) + 1] = {0};
  for (j = 0; j < (8*sizeof(unsigned int) + 1); j++) {
    mask[j] = (value << j) & (1 << (8*sizeof(unsigned int)-1)) ? '1' : '0';
  }
  printf("value is b%s\n", mask);
  return 0;
}
于 2013-11-06T21:46:13.540 回答
0

尝试这个:

#include<stdio.h>
int main(void) {

int a,i,k=1;
int arr[32]; \\ taken an array of size 32

for(i=0;i <32;i++) 
{
    arr[i] = 0;   \\initialised array elements to zero
}

printf("enter a number\n");
scanf("%d",&a);  \\get input from the user

for(i = 0;i < 32 ;i++)
{
    if(a&k)    \\bit wise and operation
    {
        arr[i]=1;
    }
    else
    {
        arr[i]=0;
    }
    k = k<<1; \\left shift by one place evry time
}
for(i = 31 ;i >= 0;i--)
{
    printf("%d",arr[i]);   \\print the array in reverse
}

return 0;
}
于 2014-12-04T12:47:21.300 回答