I write a function which should extract from unsigned int
deferrent sets of bits.
I want to use a masks for that.I am not sure what is the best way to define such masks.
For example I need to extract bits 6:14.So I need to define a mask as 111111111 << 6
.
My problem is I can't use boost or something like this and standard c/c++ doesn't know to work with binary numbers.
What is possible to do is to use 111111111 as 2^10-1.I am not sure - this is the best (most elegant ) solution.Any advices?
-
the problem is not clear enough. don't tell us about mask only, tell us also about the real problem. – Nawaz Jan 09 '13 at 14:33
-
You could use user-defined string literals for that. There was [a similar question](http://stackoverflow.com/questions/14220217/) regarding large numbers recently. – Bartek Banachewicz Jan 09 '13 at 14:36
-
http://stackoverflow.com/questions/537303/binary-literals ? – Marc Glisse Jan 09 '13 at 14:38
-
To create a mask for `2^10-1` you could use `(1<<10)-1`. – Jerry Coffin Jan 09 '13 at 14:43
4 Answers
Most people use hexadecimal when representing masks, such as 0xFF, 0x0A, etc.

- 22,531
- 20
- 68
- 106
Let's try to make a bunch of ones first.
One property of a sequence of N ones in binary is that, just like a sequence of nines in decimal, if you add one to it, you get a one followed by a N zeros. We can use the inverse, the fact that if you subtract one from a one followed by N zeros gets you a sequence of N ones, to make that.
A one followed by N zeros is just 1 shifted right N places.
template <typename Uint>
Uint zigamorph(int n) { // http://catb.org/jargon/html/Z/zigamorph.html
return 1 << n - 1; // same as 2^n - 1 :)
}
Armed with zigamorphs of any length, you can now get the bits you want from any value easily by using bitwise and.
template <typename Uint>
Uint mask_bits(Uint value, int first_bit, int last_bit) { // both inclusive?
return value & zigamorph<Uint>(last_bit-first_bit+1);
}

- 228,013
- 71
- 433
- 510
Do you have access to the standard library? If so, I would try std::bitset
Here is the documentation for it.

- 4,227
- 17
- 36
-
3If the question is tagged [tag:c++], you can safely assume that you can use standard library, unless explicitly stated otherwise. – Bartek Banachewicz Jan 09 '13 at 14:38
Just use 0x1FF << 6
(if you want 111111111 << 6
) or 0x3FF
<< 6
(if you want 2^10-1 << 6). That's considerably clearer
than your binary. As Jerry Coffin points out, you can easily
get 2^10 by using 1 << 10
, but I'm not convinced that this is
clearer than just using hexadecimal. (For that matter,
in some contexts, 0x7FC00
might be perfectly clear. It has
the advantage that you see visually exactly where the bits are
in the word, and it's easier to pick them out if you have a hex
dump.)

- 150,581
- 18
- 184
- 329