[转载] C++位运算:将一个4字节整数的二进制表示中的001替换为011

#include <iostream>
#include <assert.h>


/**
* Key:
* * get someone bit: num & (mode1bit<<N)
* * check a few bits: num & (mode3bit<<shift) == What
*/
int replace(int num)
{
    unsigned int mode3bit = 7;
    unsigned int mode1bit = 1;
    int shift = 0;
    int result = 0;
    while (shift < 32)
    {
        while (shift < 32 && (num & (mode3bit<<shift)) != (1<<shift))
        {
            result += (num & (mode1bit<<shift));
            shift++;
        }
        if (shift >= 32)
        {
            break;
        }
        else if (32 - shift < 3)
        {
            result += (num & (mode3bit<<shift));
            break;
        }
        result += (3<<shift);
        shift += 3;

    }
    return result;
}