gpt4 book ai didi

c - 符号扩展至 16 位

转载 作者:行者123 更新时间:2023-11-30 19:49:45 26 4
gpt4 key购买 nike

我将 int 数字转换为二进制,但如果二进制为 011,我需要将符号扩展为 16 位,即我需要以 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);
}
}

最佳答案

这是我的 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

关于c - 符号扩展至 16 位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11063477/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com