# Thread: Binary Format and 2's Complement Question

1. ## Binary Format and 2's Complement Question

I've got an assignment to write a program that takes a decimal, and prints it's binary format, the 1's complement of the binary format, and the 2's complement of the binary format.

So far I've come up with the following solution:

Code:
```#include "stdafx.h"
#include "conio.h"
#include "math.h"

int _tmain(int argc, _TCHAR* argv[])
{
int n, k, c;
printf("Enter an integer in decimal number system\n");
scanf("%d", &n);

printf("%d in binary number system is:\n", n);

for (c = 31; c >= 0; c--)
{
k = n >> c;
if (k & 1)
printf("1");
else
printf("0");
}

printf("\n\n");

printf("%d's complement is:\n", n);

for (c = 31; c >= 0; c--)
{
k = n >> c;
if (k & 1)
printf("0");
else
printf("1");
}

_getch();
return 0;
}```
This way the binary conversion is working, but it starts the number with a bunch of 0s, based on c's value. And because of this, the complement will include a bunch of 1's that are not needed. Moreover, I have absolutely no idea how it'd be possible to add +1 to the created number, so that we get the 2's complement.

Could you please help me with this, I'm sure there's a better way to start the whole process, but I could only find alternatives based on functions, and we haven't learned about those yet.

Thanks very much!

2. Originally Posted by sackboy127
This way the binary conversion is working, but it starts the number with a bunch of 0s, based on c's value. And because of this, the complement will include a bunch of 1's that are not needed.
I think you have to study how one's complement works. The 1's at the beginning are important.

Bye, Andreas

3. Yes, I've come up with a solution that I think takes that into consideration as well. Basically, after scanning a number, I create 2 variables, the first one is "~number", and the second is "~number + 1". This way I create the complements while in decimal format, and convert each of the 3 into binary one by one. So far it seems to be working.

4. The real challenge here is to do it in a portable manner.
I.e. print the two's-complement correctly when compiled on a one's-complement system and vice versa, as well as getting rid of that magic number 31 etc.