Created
November 13, 2019 21:38
-
-
Save samatjain/18b45fdc75c44b0585696c8be1f0def3 to your computer and use it in GitHub Desktop.
lowest_bits_set.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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