Binary linear zeros in C / C ++

If an integer is given, how do I remove leading zeros from its binary representation?

I use bitwise operators to control its binary representation. I am trying to figure out if an integer is a palindrome in its binary representation. I know there are different solutions, but I wanted to compare the first and last bit, the second and last, but one bit and so on. So, I was wondering how to remove those that lead 0 for this int.

+3
source share
4 answers

You can use BitScanForwardand BitScanReverse(exact names may differ from the compiler) to efficiently trim (well, skip processing) zeros on both sides.

+2
source

, 2 :

/* from Bit Twiddling Hacks */
static const unsigned int MultiplyDeBruijnBitPosition[32] = 
{
    0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30,
    8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31
};

uint32_t pos = value;
pos |= pos >> 1;
pos |= pos >> 2;
pos |= pos >> 4;
pos |= pos >> 8;
pos |= pos >> 16;
pos = MultiplyDeBruijnBitPosition[(uint32_t)(pos * 0x07C4ACDDU) >> 27];

, , 2:

/* adapted from Bit Twiddling Hacks */
uint32_t mask = value - 1;
mask |= mask >> 1;
mask |= mask >> 2;
mask |= mask >> 4;
mask |= mask >> 8;
mask |= mask >> 16;
+1

, , :

    #include <bitset>
    #include <string>
    using namespace std;

    // your number
    int N;
    ...

    // convert to a 32 bit length binary string
    string bitstr = bitset<32>(N).to_string();

    // get the substring
    int index = 0;
    string strippedstr;
    for(unsigned int i = 0; i < bitstr.length(); ++i) {
        if(bitstr[i] == '1') {
            index = i;
            break;
        }
    }
    strippedstr = bitstr.substr(index);
   ...
+1

, ?

:

/* flip n */
unsigned int flip(unsigned int n)
{
    int i, newInt = 0;
    for (i=0; i<WORDSIZE; ++i)
    {
        newInt += (n & 0x0001);
        newInt <<= 1;
        n >>= 1;
    }
    return newInt;
}

:

int flipped = flip(n);
/* shift to remove trailing zeroes */
while (!(flipped & 0x0001))
    flipped >>= 1;

, int , :

return n == flipped;
0

All Articles