J Walker
J Walker

Reputation: 23

Incorrect data shown for binary representation of data C++

I'm trying to output the binary representation of the number 115 using the code below, but my results shown are incorrect.

I'm expecting 0000 0000 0111 0011 but 0000 0000 0111 1111 is shown.

It seems that after determining a 1 should be shown, that's all it will show.

void Bits::displayShort(short input)
{
    cout << endl;

    sMask = 1000000000000000;

    for (int count = 0; count < 16; count++)
    {
        if ((input & sMask) == 0)
        {
            cout << "0";
        }
        else
        {
            cout << "1";
        }

        if (count == 3 || count == 7 || count == 11) { cout << " "; }

        sMask = sMask >> 1;
    }

    cout << endl << endl;
}

Upvotes: 1

Views: 46

Answers (2)

R Sahu
R Sahu

Reputation: 206697

You have couple of mistakes.

  1. Initial value of sMask -- it needs to be (1 << (8*sizeof(short)-1)).

    short sMask = (1 << (8*sizeof(short)-1));
    
  2. You need to change the value of input in the loop, not the value of sMask.

    Instead of

    sMask = sMask >> 1;
    

    You need

    input = input << 1;
    

    You can shorten that to:

    input <<= 1;
    

Upvotes: 1

Barry
Barry

Reputation: 303387

You're starting with:

sMask = 1000000000000000;

That's not a power of 2. You should be starting with the largest bit in a short, which is:

sMask = 0x8000;

Or we could use an expression, which is less error-prone:

sMask = 1 << 15;
sMask = 1 << (sizeof(input)*8 - 1);

Or in C++14, we have binary literals, which is probably what you'd intended:

sMask = 0b1000000000000000;

Upvotes: 4

Related Questions