Skip to content

Instantly share code, notes, and snippets.

@samatjain
Created November 13, 2019 21:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samatjain/18b45fdc75c44b0585696c8be1f0def3 to your computer and use it in GitHub Desktop.
Save samatjain/18b45fdc75c44b0585696c8be1f0def3 to your computer and use it in GitHub Desktop.
lowest_bits_set.cpp
#include <bitset>
#include <cassert>
#include <iostream>
using MaskType = uint64_t;
static int LowestBitSet(const MaskType v)
{
return __builtin_ffsl(v);
}
static MaskType RemoveLowestSetBit(MaskType v)
{
assert(v != 0);
return v & (v - 1);
}
static void PrintBits(const MaskType v)
{
using namespace std;
MaskType c = v; // cursor
cout << "decimal=" << v
<< " binary=" << bitset<sizeof(MaskType) * 8>(v)
<< " items=[ ";
while (c != 0) {
int i = LowestBitSet(c);
cout << i << " ";
c = RemoveLowestSetBit(c);
}
cout << "]" << endl;
}
int main()
{
PrintBits(3); // 011 = 1 and 2
PrintBits(5); // 101 = 1 and 3
PrintBits(6); // 110 = 2 and 3
PrintBits(7); // 111 = 1, 2, 3
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment