0
#include <iostream>

using namespace std;

int main() {
    int n;

    cin >> n;
    cout << (n<<1);

    return 0;
}

The left shift operator is shifting the leading zeros. For example,

for n = 5, 101 should be left shifted to 011

I want output to be 3 for n = 5 but instead it is 10 cause of the leading zeros getting shifted.

I went through all other answers, but they were not as what I expected.

Another approach to shift bits is also appreciated.

  • 3
    You do not understand how bit-shift works... n<<1 is n*2 – immortal Aug 16 '18 at 08:19
  • 3
    First read about how bit shift operator works. You can't simple expect what you want to see. – P0W Aug 16 '18 at 08:19
  • 2
    A bit shift will, by definition, shift ALL bits. If I understood correctly you wish to only shift the `1`s to the side, but have them, sort of "collide" with the end? – Qubit Aug 16 '18 at 08:19
  • Ok, I'll try shifting bits using strings without shift operator. – Arihant Bedagkar Aug 16 '18 at 08:26
  • 1
    _`101` should be left shifted to `011`_ Wouldn't this mean right shifting? (ignoring the fact that this is not how bit shift works in C++) – Scheff's Cat Aug 16 '18 at 09:48
  • After lot of research, I found this: https://stackoverflow.com/questions/25799215/bitwise-rotation-circular-shift – Arihant Bedagkar Aug 16 '18 at 10:20
  • OK, so you want a rotate left - for how many bits? Always 3, or just up to the leftmost non-zero bit? – Useless Aug 16 '18 at 11:52
  • upto left-most non-zero bit @Useless – Arihant Bedagkar Aug 16 '18 at 12:17
  • it'll be much easier to do as a string then, but if you figure out how to find out the maximum set bit, it's still easy enough to do with integers. Just reset the top bit after shifting left and then set the bottom bit to 1, being careful in case the top bit was #31 before shifting. – Useless Aug 16 '18 at 12:31
  • @Useless, Still looking for help... What exactly I want is, I want to left circular rotate from the leftmost 1-bit, exactly 1 time. for example, lets say I have a number, `n = 5`, its 32-bit binary form would be `000...00101`. According to the definition of left shift operator, the msb becomes the lsb and so after 1 left shift, it becomes, `000...01010`, which is `10` in decimal (or `n * 2`). I want it like this, `000...00101` to be circular shifted to `000...00011`, or rather how to left shift the bits when msb is 1? – Arihant Bedagkar Aug 16 '18 at 16:39
  • Unset the leftmost set bit, shift the thing to the left once, then set the rightmost bit. – eesiraed Aug 16 '18 at 23:20
  • _left shift operator, the msb becomes the lsb_ - no! That is rotation, that's why I said rotation. Left shift zero-fills the bottom bit and discards the top one (the instruction probably moves msb into the carry flag, but C++ doesn't expose this) – Useless Aug 17 '18 at 07:52
  • Anyway, make some effort. Show some code, even if it doesn't work yet. – Useless Aug 17 '18 at 07:54

0 Answers0