Write a program to print 1`s and 2`s complement of a number in binary, decimal, octal and hexadecimal format.
#include<stdio.h> void Print_Num_inBinary(int); int Num_1s_Complement(int); int Num_2s_Complement(int); int main() { int num,No1sComp,No2sComp; printf("Enter a Number = "); scanf("%d",&num); No1sComp = Num_1s_Complement(num); No2sComp = Num_2s_Complement(num); printf("1s Complement of Number %d in Decimal is = %d\n",num,No1sComp); printf("2s Complement of Number %d in Decimal is = %d\n",num,No2sComp); printf("\n1S Complement in BInary \n"); Print_Num_inBinary(No1sComp); printf("2S Complement in BInary \n"); Print_Num_inBinary(No2sComp); printf("1s Complement of Number %d in Octal is = %o\n",num,No1sComp); printf("2s Complement of Number %d in Octal is = %o\n",num,No2sComp); printf("1s Complement of Number %d in HexaDecimal is = %x\n",num,No1sComp); printf("2s Complement of Number %d in HexaDecimal is = %x\n\n",num,No2sComp); return 0; } int Num_1s_Complement(int n) { n = ~n; return n; } int Num_2s_Complement(int n) { n = Num_1s_Complement(n) + 1; return n; } void Print_Num_inBinary(int n) { int i; printf("\n%d Bit Binary Representation of a Number\n",sizeof(int)*8); for(i = ((sizeof(int)*8)-1);i >= 0;i--) { printf("%d",n >> i & 1); if(!(i%8)) printf(" "); } printf("\n\n"); }
Output
Enter a Number = 25 1s Complement of Number 25 in Decimal is = -26 2s Complement of Number 25 in Decimal is = -25 1S Complement in BInary 32 Bit Binary Representation of a Number 11111111 11111111 11111111 11100110 2S Complement in BInary 32 Bit Binary Representation of a Number 11111111 11111111 11111111 11100111 1s Complement of Number 25 in Octal is = 37777777746 2s Complement of Number 25 in Octal is = 37777777747 1s Complement of Number 25 in HexaDecimal is = ffffffe6 2s Complement of Number 25 in HexaDecimal is = ffffffe7