c - 符号扩展至 16 位

标签 c

我将 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/

相关文章:

c - 从整数子集中均匀随机选择一个数的算法

计算缓冲区中的实例数失败测试用例

c - 从c中的文件中读取多行(不同长度)

在外部服务器上编译代码(我没有根访问权限)

c - 非常奇怪的错误***glibc检测到** free()无效指针

将一个 9 位数字转换为三个 3 位数字

c - 插入双向链表的头部和尾部——仅打印最后插入的尾部项目

将 C 程序中的地址转换为源行

c - 我怎样才能按字母顺序排列这个链表?

c - 括号内的缩进而不是 emacs 中的右括号旁边