I\'m currently working on a simulation of the MIPS processor in C++ for a comp architecture class and having some problems converting from decimal numbers to binary (signed
And why can't you just cast the int
to a uint
? Then it's very easy to generate the binary string because you don't have to worry about the sign bit. Same goes for converting a binary string to an int
: build it as a uint
, and then cast it to int
:
string DecimalToBinaryString(int a)
{
uint b = (uint)a;
string binary = "";
uint mask = 0x80000000u;
while (mask > 0)
{
binary += ((b & mask) == 0) ? '0' : '1';
mask >>= 1;
}
cout<<binary<<endl;
return binary;
}
And, of course, you can apply the mentioned optimizations, like pre-allocating the string buffer, etc.
Going the other way:
uint b = 0;
for (int i = 31; i >=0; --i)
{
b <<= 1;
if (a.at(i) == '1')
b |= 1;
}
int num = (int)b;
Replace:
if((mask&a) >= 1)
with either:
if ((mask & a) != 0)
or:
if (mask & a)
Your problem is that the last bit gives you a negative number, not a positive one.
There are actually standard one-liners for these.
#include <bitset>
std::string s = std::bitset< 64 >( 12345 ).to_string(); // string conversion
std::cout << std::bitset< 64 >( 54321 ) << ' '; // direct output
std::bitset< 64 > input;
std::cin >> input;
unsigned long ul = input.to_ulong();
See this run as a demo.
The problem with 1<<=31 has been addressed in other comment. Concerning the code piece for string -> int conversion, you have several options:
or if you really want to implement the conversion yourself try the following code:
int BinaryStringToDecimal(string a)
{
int Rslt = 0;
int Mask = 1;
for (int i = a.length()-1; i >= 0; --i, Mask <<= 1) {
if (a.at(i) != '0') {
Rslt |= Mask;
}
}
return (Rslt);
}
Note that this code deals with negative numbers differently when compared with your code: in your function highest order bit is taken as signum. If the leftmost bit in string argument for your function is not in position 32 (when counting from right) your function may produce incorrect results. In the code suggested here there is no special signum treatment. But if you get the string of 32 digits with '1' as leftmost of them the MSB in int result will be == 1 and the integer will be negative (as it should be)
I checked your code and couldn't find any error. Here is the code that i used...
#include <iostream>
#include <string>
using namespace std;
int main ()
{
int a=1111165117;
string binary ("");
int mask = 1;
for(int i = 0; i < 31; i++)
{
if((mask&a) >= 1)
binary = "1"+binary;
else
binary = "0"+binary;
mask<<=1;
}
cout<<binary<<endl;
system("PAUSE"); //optional if not using ideone
return EXIT_SUCCESS; //optional if not using ideone
}
Output will be 1001110001010110101111010011101. I you can run this on ideone