Skip to content

Instantly share code, notes, and snippets.

@AldoMX
Created March 17, 2015 07:31
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 AldoMX/526e84da13b00ac0c75e to your computer and use it in GitHub Desktop.
Save AldoMX/526e84da13b00ac0c75e to your computer and use it in GitHub Desktop.
/*
* This file was written by Aldo Fregoso, and is placed in the public domain.
* The author hereby disclaims copyright to this source code.
*/
#ifndef UTIL_BITFIELD_H
#define UTIL_BITFIELD_H
#include <inttypes.h>
class bitfield32_t
{
uint_fast32_t m_field = 0;
public:
inline bool get( const size_t pos ) const
{ return (bool)(m_field & (1 << pos)); }
inline bool operator[]( const size_t pos ) const
{ return get(pos); }
inline uint_fast32_t getField() const
{ return m_field; }
inline bool isEmpty() const
{ return m_field == 0; }
inline void set( const size_t pos )
{ m_field |= 1 << pos; }
inline void clear( const size_t pos )
{ m_field &= ~(1 << pos); }
inline void toggle( const size_t pos )
{ m_field ^= 1 << pos; }
inline void setAll()
{ m_field = ~0; }
inline void clearAll()
{ m_field = 0; }
inline void toggleAll()
{ m_field ^= ~0; }
uint_fast32_t getNumSettedBits() const {
//
// Code Taken from:
// http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
//
uint_fast32_t bits = getField();
bits = bits - ((bits >> 1) & 0x55555555);
bits = (bits & 0x33333333) + ((bits >> 2) & 0x33333333);
return ((bits + (bits >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
}
uint_fast32_t getNumClearedBits() const
{ return 32 - getNumSettedBits(); }
inline void operator=( const bitfield32_t& other ) { m_field = other.m_field; }
inline bool operator==( const bitfield32_t& other ) const { return m_field == other.m_field; }
inline bool operator!=( const bitfield32_t& other ) const { return m_field != other.m_field; }
};
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment