Combining two-bit patterns

I need to combine two variables. They are both unsigned ints.

  • First: 11,000,000
  • Second: 11111010000

Required output: 11011111010000

In words: I need to put all 1, followed by 0 (in the first number) in front of the whole second number. The only thing that comes to my mind is to beat to shift the first number to the left as well as the length of the second. And summarize it. But I do not know the length. Although it can probably be found, is there a better way?

thank

+3
source share
3 answers

, 1 0. "" 1 ( ) , .

+1

, :

1- x by (int) (log (x)/log (2)).

, x , : http://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightMultLookup

, :

int x, y;
int lookuptable[32] = { 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25,
                        17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 
                        12, 18, 6, 11, 5, 10, 9 };

int tail_x = lookuptable[(((x & -x) * 0x077CB531U)) >> 27];
int size_y = (int)(log(y) / log(2)) + 1;

if (tail_x - size_y <= 0) {
        x <<= size_y - tail_x + 1;
} else {
        x >>= tail_x - size_y - 1;
}       

x |= y;

x y x, OP. , 32- .

+2

, 2

unsigned int v;// , v 2 bool f;//

f = (v (v - 1)) == 0; , 0 2 . , : f = v & &! (v (v - 1));

, , v 1 2, v (v + 1) v) == 0

( + 1) )!= 0

, Jon, != 0 (copy + 1) )!= 0 , theres int 1 . for, ( < (cBitsFirst + 1)) | ;

unsigned int first, second; // initialize these somehow
unsigned int result = 0;
int cBitsFirst = 0;
unsigned int copy;
for (copy; (copy + 1) & copy) != 0; copy >>= 1) {//stop when there is series of 0 followed by a series of 1's
    ++cBitsFirst;
}

result = (copy << (log2(second)+1) | second;//the plus one gives the 0 back
0

All Articles