Question: I was playing with bitwise operations and a question about counting true bits of any positive integer value, so I solved the problem with bit shifting, so I just thought if there would be some way to get shifted or unshifted bits from the bitwise operation, Code would be more optimized. So I checked the PHP documentation and I learnt bitwise operations directly translated to the C code. I checked C and I didn't see any related section. So do you have any idea about that ? Is this possible to get these bits ? Or it just throwed away ?

The code that I'm trying to optimize :

```
function num1Bits($number)
{
    if ($number <= 0) {
        return 0;
    }

    $countOf1 = 0;

    do {

        if ($number & 1) {
            ++$countOf1;
        }

    } while ($number = $number >> 1);

    return $countOf1;
}

echo num1Bits(11);

```

Any information would be appreciated.

Answer: 
The bitwise shift-left (`<<`) and shift-right (`>>`) in higher level languages such as PHP, C or C++ ***lose*** the most or least significant bit. 

However, with many CPUs, the assembly instruction for shifting doesn't really lose this bit but [shift it into the carry forward flag](http://www.c-jump.com/CIS77/ASM/Flags/F77_0140_shl_sal_instructions.htm). So you could then react on this [carry flag](https://en.wikipedia.org/wiki/Carry_flag), as explained in [this SO question](https://stackoverflow.com/questions/3139772/check-if-carry-flag-is-set). 

By the way in assembly, depending on your CPU, you often not only have shifting operations but also [rotating instruction](https://en.wikibooks.org/wiki/X86_Assembly/Shift_and_Rotate#Logical_Shift_Instructions) with or without taking into account the carry forward flag.
well certainly you just mask them off before the shift if you dont want to lose them.

Some instruction sets have a rotate which moves them around to the top, this is not reflected in high level languages (PHP, C, etc). Sometimes they rotate through the carry. Likewise as already mentioned sometimes they shift through the carry before being discarded.

If your goal is to both shift and save what is shifted off, then simply mask the bits off before shifting and save them that way, pretty much any useful programming language (has some minimal bitwise operations, and, or, not, etc) will support this.