#include <stdio.h>
#include <stdlib.h>
char * getComplement(int num, int len);
int main(void){ int num; int len = sizeof(int) * 8; printf("%s\n", "please enter a number:"); scanf("%d", &num); char * complement = getComplement(num, len); printf("the number %d 's complement is :\n%s\n", num, complement); free(complement); return 0; }
//获取一个num数的补码 char * getComplement(int num, int len){ int i; int data = (1<<(len - 1)); char * retVal = (char * )malloc(sizeof(char) * (len / 4 - 1));; int j = 0; for (i = 0; i<len; i++){ if(i %4 == 0 && i != 0){ sprintf(retVal + (j++), "%c", ' '); } sprintf(retVal + (j++), "%c", ((num & data) == data)? '1': '0'); num<<=1; } return retVal; }