Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a clever way to "double up" bits in an integer?

Tags:

c++

math

binary

Say I have the binary number 0b00110101.

Is there a set of trivial arithmetic operations that will produce 0b0000111100110011, where every bit of the first word is repeated twice?

Does such a trivial function exist to repeat bits 3, 4, or N times?

like image 862
Eric Avatar asked Jan 14 '13 00:01

Eric


2 Answers

Have a look at this document:

https://web.archive.org/web/20140629081102/http://www-graphics.stanford.edu/~seander/bithacks.html#InterleaveBMN

It describes interleaving two 16-bit numbers, and it's fairly trivial to extend it to 32-bit numbers (this creating a 64-bit number). You just continue the pattern for one extra cycle. Like this:

static const unsigned long long B[] = {
    0x5555555555555555,
    0x3333333333333333,
    0x0F0F0F0F0F0F0F0F,
    0x00FF00FF00FF00FF,
    0x0000FFFF0000FFFF
};
static const unsigned int S[] = {1, 2, 4, 8, 16};

unsigned long long x; // x must initially fit inside 32 bits
unsigned long long z; // z gets the result of x interleaved with itself

x = (x | (x << S[4])) & B[4];
x = (x | (x << S[3])) & B[3];
x = (x | (x << S[2])) & B[2];
x = (x | (x << S[1])) & B[1];
x = (x | (x << S[0])) & B[0];

z = x | (x << 1);
like image 61
paddy Avatar answered Nov 02 '22 20:11

paddy


I would make a table - it's PROBABLY the quickest way.

You could of course do this:

 int doublebits(int x)
 {
     int y = 0;
     int bit = 0;
     while(x)
     {
        if (x & 1)
            y |= 3 << bit;
        bit += 2;
        x >>= 1;
     }
     return y;
 }

For an 8-bit number, you'll do at most 8 shifts down, and 8 shifts to the right to make the new number.

like image 44
Mats Petersson Avatar answered Nov 02 '22 20:11

Mats Petersson