1

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?

larsmoa
  • 12,604
  • 8
  • 62
  • 85
YAKOVM
  • 9,805
  • 31
  • 116
  • 217

4 Answers4

3

Most people use hexadecimal when representing masks, such as 0xFF, 0x0A, etc.

Rocky Pulley
  • 22,531
  • 20
  • 68
  • 106
2

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);
}
R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
1

Do you have access to the standard library? If so, I would try std::bitset

Here is the documentation for it.

lcs
  • 4,227
  • 17
  • 36
1

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.)

James Kanze
  • 150,581
  • 18
  • 184
  • 329