程序代码:
#include <stdio.h>
#include <limits.h>
char * to_binary_str(char * buffer, int value)
{
int i;
for (i = sizeof(int) * 8 - 1; i > -1; i--)
buffer[31 - i] = ((value >> i) & 1) + '0';
buffer[sizeof(int) * 8] = '\0';
return buffer;
}
int main(void)
{
char buffer[33];
int n;
scanf("%d", &n);
if (n >= 0) {
printf("反码:%s\n", to_binary_str(buffer, n));
printf("补码:%s\n", to_binary_str(buffer, n));
printf("原码:%s\n", to_binary_str(buffer, n));
} else {
if (n == INT_MIN)
printf("反码:1%s\n", to_binary_str(buffer, ~n));
else
printf("反码:%s\n", to_binary_str(buffer, n - 1));
printf("补码:%s\n", to_binary_str(buffer, n));
if (n == INT_MIN)
printf("原码:1%s\n", to_binary_str(buffer, n));
else
printf("原码:%s\n", to_binary_str(buffer, ~n + 1 | INT_MIN));
}
return 0;
}