-4

Using bitwise operators left or right shift, moves every bit left or right. int x{5};

decimal|binary

5 =00000000 00000000 00000000 00000101 (because int is 4 bytes,32bits)

x=(x<<1);

The bits that move out are discarded and the bits that come in are 0.

decimal|binary

10 =00000000 00000000 00000000 00001010

If these are memory locations and our memory contains junk, why the bits that are inserted are always zero. Is there something that is setting them to zero?

  • 1
    Provide a [mcve] which demonstrates the behavior you claim please. – πάντα ῥεῖ Dec 21 '20 at 11:23
  • 1
    Because that's how the shift operator is supposed to work? It doesn't shift the entire memory, it only shifts the "word" you're specifying, and adding zero bits at the end. Perhaps you should invest in [some good C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)? And I also recommend you find a book or a class on low-level (assembly) programming to learn how computers work. – Some programmer dude Dec 21 '20 at 11:24
  • What do you expect a bitshift to the left do? Should it magically create bits 0s and 1s out of nowhere? – Raildex Dec 21 '20 at 11:27

1 Answers1

0

This is just how shift works by definition. When you "move" the bits over, you pad the gap with zeroes. Remember that x <<= 2 in base-2 is like x *= 100 in base-10. What do you do when you multiply by 100? You basically add zeroes.

As in, if you had a random "junk" number like NNN then that times 100 is, by definition, NNN00, regardless of what the number actually is.

This is only true for powers of the base, as in 0, 10, 100, 1000, etc. in base-10, or 0, 2, 4, 8, etc. for base-2. The same holds true for any base, like octal would be 0, 8 (010), 64 (0100), etc. or for hexadecimal 0, 16 (0x10), 256 (0x100), etc.

Since that's the definition, in hardware the bit shifting is implemented as moving the bits over from one spot in the register to another, kicking them along a certain number of places, filling in the gaps with zeroes.

tadman
  • 208,517
  • 23
  • 234
  • 262