Converting a ‘long’ type into a binary String

My objective is to write an algorithm that would be able to convert a long number into a binary number stored in a string.

Here is my current block of code:

#include<iostream>
#define LONG_SIZE 64; // size of a long type is 64 bits

using namespace std;

string b10_to_b2(long x)
{
    string binNum;
    if(x < 0) // determine if the number is negative, a number in two's complement will be neg if its' first bit is zero.
    {
            binNum = "1";
    }
    else
    {
            binNum = "0";
    }
    int i = LONG_SIZE - 1;
    while(i > 0)
    {
            i --;
            if( (x & ( 1 << i) ) == ( 1 << i) )
            {
                    binNum = binNum + "1";
            }
            else
            {
                    binNum = binNum + "0";
            }
    }
    return binNum;
}

int main()
{
    cout << b10_to_b2(10) << endl;
}

The output of this program is:
00000000000000000000000000000101000000000000000000000000000001010
I want the output to be:
00000000000000000000000000000000000000000000000000000000000001010

Can anyone identify the problem? For whatever reason the function outputs 10 represented by 32 bits concatenated with another 10 represented by 32 bits.

Thank you


Source: c++

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.