9

I have an std::bitset and the bitset type also provides a to_ulong method to translate the bitset into a number, my problem is about translating the bitset into a number while just considering a range in that bitset, I need to implement my own powerof2 function or there is something with a more standard approach ?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
user2485710
  • 9,451
  • 13
  • 58
  • 102

2 Answers2

8

You can drop the unnecessary bits like

#include <bitset>
#include <iostream>

// drop bits outside the range [R, L) == [R, L - 1]
template<std::size_t R, std::size_t L, std::size_t N>
std::bitset<N> project_range(std::bitset<N> b)
{
    static_assert(R <= L && L <= N, "invalid bitrange");
    b >>= R;            // drop R rightmost bits
    b <<= (N - L + R);  // drop L-1 leftmost bits
    b >>= (N - L);      // shift back into place
    return b;
}

int main()
{
    std::bitset<8> b2(42); // [0,0,1,0,1,0,1,0]
    std::cout << project_range<0,8>(b2).to_ulong() << "\n"; // 42 == entire bitset
    std::cout << project_range<2,5>(b2).to_ulong() << "\n"; // 8, only middle bit
}

Live example with output.

TemplateRex
  • 69,038
  • 19
  • 164
  • 304
  • @user2485710 I made some mistakes in the original version. This one is tested, see the live example. – TemplateRex Jul 25 '13 at 12:25
  • wait, doesn't work for me, in this case http://ideone.com/RNJXNH my program should print 15, it prints 120 because it doesn't drop the rightmost bits ... – user2485710 Jul 25 '13 at 12:46
  • 1
    @user2485710 bits [3, 7) *as a subset of [0,32)* represents 120, if you rightshift that another 3 bits, you get 15. If that is the behavior you want, simply change the last statement to: `b >>= (num - l + r);` – TemplateRex Jul 25 '13 at 13:05
2

You can use string as intermediate storage:

bitset<32> bs (string("1011"));
cout << bs.to_ullong() << endl;

// take a range - 2 last bits in this case
string s = bs.to_string().substr(bs.size() - 2);  

bitset<32> bs1 (s);
cout << bs1.to_ullong() << endl;

Prints:

11
3
Alex F
  • 42,307
  • 41
  • 144
  • 212
  • nice to have options, but I think that this creates unnecessary temporary variables . I need to shrink my steps into a very small number. – user2485710 Jul 25 '13 at 12:24