Possible Duplicate:
Efficiently convert between Hex, Binary, and Decimal in C/C++
Im taking an Assembly Language class and was asked to write an application to accept a signed integer as input and output the corresponding 2’s complement. I’ve been all over the internet trying to find code that would help, but the only thing that I can find is code that converts into exact binary (not the 16-bit format that I need with the leading zeroes). This is the code I have so far:
#include<iostream>
#include<string>
using namespace std;
string binaryArray[15] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
void toBinary(int);
void convertNegative();
int main()
{
cout << "This app converts an integer from -32768 to 32767 into 16-bit 2's complement binary format" << endl;
cout << "Please input an integer in the proper range: ";
int num;
cin >> num;
if (num < -32768 || num > 32767)
cout << "You have entered an unacceptable number, sorry." << endl;
if (num < 0)
{
toBinary(num);
convertNegative();
}
else
toBinary(num);
cout << endl;
system("pause");
return 0;
}
My toBinary function was the function you can find on the internet for decimal to binary, but it only works if I am outputting to the console, and it doesn’t work on negative numbers, so I can’t take the 2’s complement. Any ideas?
To compute the two’s complement of a number, you invert the number (change all of its 0 bits to 1, and all of its 1 bits to 0), and then add one. It’s that simple. But you’d only need to do that if the number is negative in the first place; the two’s complement of a non-negative number is simply the number itself (unconverted).
But you’re taking a number as input, and storing it in your variable ‘num’. That variable IS in two’s complement form. That’s how your computer stores it. You don’t need to “convert” it to two’s complement form at all! If you simply shift the bits off one at a time & print them, you get the two’s complement of that number. Just shift them in the right order & pick off the leftmost bit each time, and you’ve got your solution. It’s really short & simple.