-1

I want to construct the unsigned integer (4 bytes) represented by the binary string 10101010101010101010101010101010 (that's 16 1s and 16 0s).

Is there an efficient way to construct this value using bit manipulation? I could do it in a for loop, but I feel that's inefficient.

Any language works for me. I personally know c and C++.

dangerChihuahua007
  • 20,299
  • 35
  • 117
  • 206

2 Answers2

5

Just read bits 4 by 4 and treat them as hex:

your number is just 0xAAAAAAAA.

Emilio Garavaglia
  • 20,229
  • 2
  • 46
  • 63
1

With a fixed number of bits, this is a bit obvious...

But for a variable number of bits, such pattern can be obtained by integer division as demonstrated here http://smallissimo.blogspot.fr/2011/07/revisiting-sieve-of-erathostenes.html

EDIT More detailed explanations below:

The idea is that :

2r01 * 2r11 -> 2r11
2r0101 * 2r11 -> 2r1111
2r010101 * 2r11 -> 2r111111

So inversely, we can apply an exact division:

2r111111 / 2r11 -> 2r010101

If we want 2r101010 rather than 2r010101, just add 1 more bit (but the division is then inexact, I assume quotient is given by // like in Smalltalk) :

2r1111111 // 2r11 -> 2r101010

2r1111111 can be constructed easily, it is a power of 2 minus 1, 2^7-1, which can also be obtained by a bith shift (1<<7)-1.

In your case, your constant is ((1<<33)-1)//3, or if you write it in C/C++ ((1ULL<<33)-1)/3
(In Smalltalk we don't care of integer length, they are of arbitrary length, but in most language we must make sure the operands fits on a native integer length).

Note that division also work for bit patterns of longer length like 2r100100100, divide by 2r111, and for a bit pattern of length p, divide by 2^p-1 that is (1<<p)-1

aka.nice
  • 9,100
  • 1
  • 28
  • 40
  • That was not a question. – Ramon Snir Jun 09 '13 at 17:13
  • @RamonSnir The question is how to construct, so this might be an answer, though I agree, the answer is useless if the pattern is of fixed length – aka.nice Jun 09 '13 at 19:37
  • At least summarize the formula `(2^64-1)*2/3` (the article is long and mostly irrelevant). But the question was about fixed size. I will not that this "trick" doesn't work for all powers of two, only the even ones. – Ramon Snir Jun 09 '13 at 19:52
  • @RamonSnir yes it was a lazy answer, because too much for calculating a constant! But the article is relevant, the essence of the algorithm is precisely this property of bit division and it is right at the beginning of the article. I edited now to make sure there is no mis-understanding, the algorithm should work for any bit length. – aka.nice Jun 09 '13 at 20:47