0

I'm having an issue shifting bits and I cannot seem to understand what is going on. I'm able to shift bits to the left perfectly fine but I am unable to shift bits to the right. Here's a look at what is going on:

Shifting to the right (works as intended):

// bits is a char that = 00011000

// Shift the bits to the left
bits = bits << 3;

// Print the bits
std::bitset<8> x(bits);
std::cout << "Shifted Bits: " << x << std::endl;

This produces the expected output of 11000000 as '00011000' has been shifted to the left 3 bits.

It looks like 1's are added instead of 0s when I attempt to shift to the right, however:

// bits = 11000000 from the previous operation

// Shift the bits to the right
bits = bits >> 5;

// Print the bits
std::bitset<8> y(bits);
std::cout << "Shifted (right) bits: " << y << std::endl;

This produces the unexpected output of 11111110 when the expected output was '00000110' as I was attempting to shift '11000000' 5 places to the right.

Is there an explanation/reason for why the shift operator is adding 0s to the new spaces when I shift to the left but then adding 1s to the new spaces when I shift to the right?

Thanks!

EDIT:

I figured out what was going on. I was extracting bits from an array of DDS_Octets but I was using a char for the bits variable. It looked like this:

DDS_Octet* buffer_ = new DDS_Octet(BUFFSIZE); 
fill_buffer(buffer_);

// Here is where the issue is
// I am implicitly casting a DDS_Octet to a char which is a no-no
char bits = buffer_[0];

// The code above now happens here

When I made 'bits' the same type as the buffer I no longer had this issue of 1s being added instead of 0's.

I'll leave this here in case someone has the same problem I did and stumbles upon this.

Walklikeapenguin
  • 127
  • 2
  • 10
  • 3
    What is the type of `bits`? Is `bits` a `signed` or `unsigned` type? – KamilCuk Aug 02 '20 at 22:30
  • 2
    Show the definition for `bits`. It looks like you're using a signed 8 8-bit value. Right shifts of negative signed values can propagate the sign. You should used an `unsigned` 8 bit type. – 1201ProgramAlarm Aug 02 '20 at 22:30

1 Answers1

1

You use a char for bits. char is signed or unsigned depending on the platform. You should use unsigned char to get a more expected behavior.

Daniel
  • 30,896
  • 18
  • 85
  • 139