我将int
数字转换为二进制,但我需要将符号扩展为16位,二进制数为011,即我需要在0000000000000011
中打印它。
如果负数的二进制值大于7,我也有一个问题。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
void main()
{
int x;
char inst[4][15]={"addi","8"};
int rem, num=0, i=1;
int y;
int num1 = atoi(inst[1]);
if (num1 < 0)
{
x=atoi(inst[1]);
x = (x * -1) -1;
printf("x %d",x);
while(x > 0)
{
rem = x % 2;
x= x / 2;
num = (rem * i)+num;
i = i * 10;
y = num ^ 111;
}
printf("binary no: %d",y);
}
else
{
x = atoi(inst[1]);
while(x > 0)
{
rem = x % 2;
x = x / 2;
num = (rem * i) + num;
i = i * 10;
}
printf("binary no: %d", num);
}
}
答案 0 :(得分:0)
这是我的32位整数代码。这会给你一个提示。
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int
5 main(void)
6 {
7 const char set[] = {'0', '1'};
8 int number;
9 unsigned int unumber, tmp;
10 int i, loop;
11 char * output, * cpy;
12
13
14 scanf("%d", &number);
15 unumber = (unsigned int)number;
16
17 loop = sizeof(unsigned int) * 8;
18 output = malloc(loop + 1);
19 cpy = output + loop;
20 *cpy = '\0';
21 cpy--;
22
23 for(i = 0; i < loop; i++)
24 *cpy-- = set[(unumber >> i & 1)];
25
26
27 printf("%s\n", output);
28 free(output);
29
30 return 0;
31 }
32
示例输入和输出:
10
00000000000000000000000000001010
-1
11111111111111111111111111111111