如何将无符号整数表示为二进制?
答案 0 :(得分:2)
要创建某个整数值的字符串表示形式,您可以使用以下code:
#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;
}
答案 1 :(得分: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;
}