如何得出二进制补码?

lizo 2003-06-19 04:31:27
从键盘输入一个整数(long类型,32个二进制位),输出其二进制补码。
...全文
149 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
lizo 2003-06-20
  • 打赏
  • 举报
回复
#include<stdio.h>
void disp_binary(long);
main()
{
long int num;
scanf("%ld",&num);
if(num>0) disp_binary(num);
else
{
num=(~num) + 1;
disp_binary(num);
}
return 0;
}
void disp_binary(long num)
{
register unsigned long k;
for(k=2147483648;k>0;k=k>>1)
{
if(k&num) printf("1");
else printf("0");
}
printf("\n");
}
i_jianyong 2003-06-20
  • 打赏
  • 举报
回复
#include <iostream>
#include <bitset>
using namespace std;

int main()
{
long num;
cin >> num;

bool negative = false;
if (num < 0)
{
num = -num - 1;
negative = true;
}

bitset<32> comp_code(num);
if (negative)
{
comp_code = ~comp_code;
comp_code.set(31);
}

cout << comp_code << endl;
}
WYC2300 2003-06-19
  • 打赏
  • 举报
回复
根据正负取反再加减~~~````~~~~~
lzh7800 2003-06-19
  • 打赏
  • 举报
回复
这个方法可以一用:
#include <iostream>

void printBinary(const long val)
{
for(int i = 31; i>=0; i--)
if(val & (1 << i))
cout<< "1";
else
cout << "0";
}

int main()
{
printBinary(64000);
}
cnxiaohai 2003-06-19
  • 打赏
  • 举报
回复
#include <stdlib.h>

这个头是什么?
老师没教过~~~~~~~~~~~~~~~~~~~~


各位大大说说~~~~~~~~~~~~~~~~~~~~~~~
arfi 2003-06-19
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main()
{
long int num;
char str[80];
int len;

printf("Input the num:");
scanf("%ld", &num);
itoa(num, str, 2);
len = strlen(str);
for(;32-len;len++)
printf("0");
printf("%s\n", str);
}
短歌如风 2003-06-19
  • 打赏
  • 举报
回复
在当前大多数机器上都是用补码表示负数(整数类型)的,直接取相反数就行了。
标准算法是“取反加一”.也就是(~Value) + 1
以二进制输出有很多方法,最简单就是用递归算法:
函数:以二进制输出a
1:如果a > 1 则以二进制输出a/2;
2:输出a%2。
lizo 2003-06-19
  • 打赏
  • 举报
回复
如输入: 64000 则程序输出:
00000000000000001111101000000000
又如何呢?
谢谢
arfi 2003-06-19
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <stdlib.h>

void main()
{
long int num;
char str[80];

printf("Input the num:");
scanf("%ld", &num);
itoa(num, str, 2);
printf("%s\n", str);
}

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧