1

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?

Community
  • 1
  • 1
Seff
  • 35
  • 3
  • 8
  • 2
    Do you *know* how binary representation and 2's complement works? I find it a bit strange that you have all of your utility code in place but haven't made the slightest attempt at implementing the *actual* algorithms. – us2012 Jan 29 '13 at 19:54
  • Why are you messing around with arrays of strings in C++ if it's an assembly language class? As far as I can tell, this is an exercise in bitwise operations and I/O. – molbdnilo Jan 29 '13 at 20:25
  • I know how it all works, that was actually the lesson that was taught. On I can do all the math on paper, but when it comes to making an actual program my brain brick walls itself. – Seff Jan 29 '13 at 20:36
  • This is the class after my C++ primer class, so I only know the very basic level of C++ programming. Arrays was just a way I was working on to help me display the proper format. I figured once I could figure out how to convert the numbers to binary and feed them into the array, then it would a simple loop to take the complement. – Seff Jan 29 '13 at 20:43

1 Answers1

2

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.

phonetagger
  • 7,701
  • 3
  • 31
  • 55
  • I wish I could upvote but I'm at my limit lol. But great answer though. :) – David G Jan 29 '13 at 20:06
  • When you say the variable IS in two's complement form, you loose me. To my understanding I am saving whatever number they inputted into my variable 'num'. So if they entered '20' then that would be stored as '20'not two's complement format '0000 0000 0001 0100' – Seff Jan 29 '13 at 20:31
  • On almost every modern computer system, integer variables *are* stored in two's complement form, you don't have to do anything special to store them that way. Your misunderstanding comes from the fact that you're not seeing that your variable `var` is simply the content of a memory location in your computer's RAM (or, at times, in a CPU register). That memory location's content can be printed out in any of various ways. If you `cout << num` and get the printout `20` as a result, then you could also `cout << hex << num << dec` and get the printout `14` as a result. The `20` and `14` are... – phonetagger Jan 29 '13 at 20:44
  • ...both representing the same number, which is held in the variable `num`. You could also use a loop with bit-shifting & masking to print the same value in binary format (I don't think that std::cout has a std::bin binary format flag). In any case, an `int` variable *is* stored in 2's complement form internally. If you do the requisite bit-shifting & masking & conditional logic to print '0' or '1', you'll print the binary representation of `num` directly, which, because your computer stores it in 2's complement form, will be in 2's complement form without any conversion required by you. – phonetagger Jan 29 '13 at 20:47
  • Alternatively, if manually computing the bits & printing them is a requirement of the assignment, then doing it the way I suggest might be considered "cheating". But any real-world code that worked manually like that would be scoffed at by anyone who understands the representation of numbers internal to a computer. – phonetagger Jan 29 '13 at 20:48
  • This is the assignment: Write a HLL application to accept a signed decimal integer as input and output the equivalent 2s complement version in 16-bit binary. Include a space between every four bits in the output string. The input will only be processed by the application if it falls in the valid range that can be represented in 2s complement format with 16 bits. – Seff Jan 29 '13 at 20:56
  • The logic he gave us was: Prompt for input in valid range Get input Display input back to user IF (input out of range) THEN Error message to user ELSE IF (input is negative) THEN Convert magnitude of input to equivalent binary string Complete the rest of the 2s complement conversion steps ELSE END IF Insert spaces between every four bits of binary string Output binary string END IF End application – Seff Jan 29 '13 at 20:56
  • @Seff - This is not a difficult assignment, whether you use the shortcut I suggested or whether you manually handle each bit. If this is one of your first attempts at programming, it may be a challenge. But give it a good try, and experiment. If what's going on in the middle of your program isn't clear, add `cout << "here I am"` messages in the middle of your code so you can trace its logic, perhaps even printing the content of a variable. You can do it. The satisfaction of making it work yourself is much better than having someone else write your code for you. – phonetagger Jan 29 '13 at 21:01
  • Im not here looking for anyone to write code for me, I just wanted a little help getting through my logic. Now you're saying that I don't need to do any conversions because I can access the binary directly through bit shifting and masking. Cool, my next problem was that I was never taught how to do that, or maybe we were but we never spent a lot of time at the bit level, so I don't remember. This is the first time I've ever had to deal with Binary in general so I am feeling more then a little lost. I've been experimenting for a day and that bit of code is what I have come up with. – Seff Jan 29 '13 at 21:19
  • @Seff - Your friends are `<<`, `>>`, `&`, `|`, and `~`. And get to know hexadecimal. Between all of those, with a `for()` loop thrown in the mix, you've got all you need. – phonetagger Jan 29 '13 at 21:28
  • So I was going the wrong direction with arrays. Thank you Phonetagger, I'll go look those up. – Seff Jan 29 '13 at 21:33
  • @Seff - So suppose I want to print just "bit 15" (high bit of a 16-bit integer value): `cout << ((num & 0x8000) ? '1' : '0');`. If I want to print "bit 14", then it would be `cout << ((num & 0x4000) ? '1' : '0');` Notice the difference between the two. You could code the whole thing with a bunch of brute force `cout` statements, or you could code it in a loop with bit shifting (i.e. shift `num` up by one bit each time, and simply print "bit 15" each time). So to shift `num` up by one bit: `num = num << 1`, or (same thing): `num <<= 1`. – phonetagger Jan 29 '13 at 21:33
  • You're supposed to also print extra spaces every 4th digit. Once you get your loop working for all 16 bits, go back & add a counter. When it gets to the 4th digit, use an `if()` statement to print the extra space (and don't forget to reset the counter back to 0). – phonetagger Jan 29 '13 at 21:35
  • Ohhhh!!!! I get it! Dude, that makes so much more sense than I have been reading online and in these frackin books. – Seff Jan 29 '13 at 21:38
  • @Seff - If that's been helpful, I'm glad. I would appreciate both an upvote and answer-selection as "payment" for my time. – phonetagger Jan 29 '13 at 21:40
  • @Seff - Thanks. I'd still appreciate a corresponding upvote for the answer as well. – phonetagger Jan 29 '13 at 22:14
  • It says that I need 15 rep to up vote, but I selected this answer, and as soon as I get 15 rep, I'll up vote it for sure. I really do appreciate your help, you have no idea how flustered I was getting over something so simple. – Seff Jan 29 '13 at 22:14
  • @Seff - Oh, man, I hate those silly rep requirements. :) – phonetagger Jan 29 '13 at 22:16
  • @phonetagger - Finally got enough rep to upvote the answer, so I did. Again, I appreciate your help. – Seff Apr 24 '13 at 20:40
  • @Seff - Wow, thanks for remembering! – phonetagger Apr 25 '13 at 03:01