q0987
q0987

Reputation: 35982

Why unsigned int right shift is always filled with '1'

#include <iostream>
#include <string>
#include <bitset>

int main()
{
    char c = 128;
    unsigned int shift2 = (unsigned int)c;
    std::string shift2bin = std::bitset<8>(shift2).to_string(); //to binary
    std::cout << " shift2bin: " << shift2bin << std::endl;

    unsigned int shift3 = shift2 >> 1;
    std::string shift3bin = std::bitset<8>(shift3).to_string(); //to binary
    std::cout << " shift3bin: " << shift3bin << std::endl;

}

Output:

 shift2bin: 10000000
 shift3bin: 11000000

I expect the result to be as follows:

 shift2bin: 10000000
 shift3bin: 01000000

Question> Why unsigned int right shift uses 1 as the filler?

Upvotes: 0

Views: 4720

Answers (1)

Ken Y-N
Ken Y-N

Reputation: 15009

As seen in this answer, unsigned right shifts always zero-fill. However, try this to print out all the bits in the unsigned int:

std::string shift2bin = std::bitset<sizeof(shift2)*8>(shift2).to_string(); //to binary
std::cout << " shift2bin: " << shift2bin << std::endl;

You will see something like (as you appear to have char signed by default):

shift2bin: 11111111111111111111111110000000
                                   ^^^^^^^^

If you do the same for shift3bin, you will see:

shift3bin: 01111111111111111111111111000000
                                   ^^^^^^^^

So, you can see how you appear to get a "1" fill.

Upvotes: 3

Related Questions