1

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;
}

2 Answers 2

4

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;
Sign up to request clarification or add additional context in comments.

Comments

1

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;
    

2 Comments

It works correctly now thanks, but why not shift the mask instead of the user input value?
You can shift the mask too if you make it unsigned short not short.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.