Skip to content

Instantly share code, notes, and snippets.

@gregbugaj
Created October 17, 2017 14:53
Show Gist options
  • Save gregbugaj/085dd6e8490b334d92c5d8836c20b8e7 to your computer and use it in GitHub Desktop.
Save gregbugaj/085dd6e8490b334d92c5d8836c20b8e7 to your computer and use it in GitHub Desktop.
Counting transitions in a bit string
template <class T> void bitstr(const T& out) noexcept;
template <class T> int popcnt(const T& val) noexcept;
int main()
{
// Uniform descriptors
// 0000 0000 (0 Transitions : Uniform) 0x0
// 1110 0011 (2 Transitions : Uniform) 0xE3
// 0101 0000 (4 Transitions : NonUniform) 0x50
// 0000 1010 (4 Transitions : NonUniform) 0xA
// 0000 1001 (3 Transitions : NonUniform) 0x9
int a = 0xE3;
int b = a >> 1;
int c = a ^ b;
int count = popcnt(c);
bitstr(a);
bitstr(b);
bitstr(c);
std::cout << "Transition : " <<count;
return 0;
}
template <class T>
int popcnt(const T& val) noexcept
{
int bitcount;
__asm__ ("popcnt %1, %1" : "=r" (bitcount) : "0" (val));
return bitcount;
}
template <class T>
void bitstr(const T& out) noexcept
{
std::bitset<CHAR_BIT * sizeof(T)> bs(out);
auto val = static_cast<int>(out);
std::cout << "0x"
<< std::setw(8) << std::hex << val << " : "
<< std::setw(8) << std::dec << val<< " :: " << bs << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment