Can you please tell me if there are any new versions of the c ++ standard or the standard library that work with bits in large data arrays.

For example, I have an array

char* buffer; 

in which it is necessary to determine the value of the n-th bit (for example, 12345th) or set such a bit or reset.

Now I use my functions:

 uint8_t get_bit ( uint8_t* buffer const uint32_t index ) const { const uint32_t bytesIndex = index/ 8; const uint32_t bitsIndex = index % 8; const uint32_t mask = (1 << bitsIndex); const uint32_t maskValue = (buffer[bytesIndex] & mask); return ((maskValue == 0) ? (0) : (1)); } void set_bit ( uint8_t* buffer const uint32_t index, const uint8_t value ) { const uint32_t bytesIndex = buffer/ 8; const uint32_t bitsIndex = buffer % 8; const uint32_t mask = (1 << bitsIndex); buffer[bytesIndex] = (value == 1) ? (buffer[bytesIndex] | mask) : (buffer[bytesIndex] & !mask); } 

which still makes it somewhat difficult to read the code :)

Maybe in C ++ 11 + there were some built-in tools, more beautiful and faster than self-written?

  • one
    bitset do not want to use? Or? at worst, vector<bool> ? - Harry
  • Why is it difficult? get_bit - set_bit - everything is clear. The only problem is that the size of the array is not transmitted anywhere and the output beyond its limits is not monitored. - VTT
  • @VTT, I copied it unnecessarily when copying the code :), so there is a check. Just thought maybe there are already built-in quick solutions (faster than my approach to the forehead) - Zhihar
  • @Harry, but it seemed to me that the vector bool would still allocate a byte for each bool - Zhihar
  • No, it will not - it keeps them packed, but it does it through ... in the sense, through a proxy. - Harry

1 answer 1

Modern processors execute linear code faster, i.e. the code does not contain branching (including the ternary operator).

Therefore, we can offer, for example, such modifications of the functions for checking and setting the bit (you can put them in any of your header files)

 static inline int get_bit (uint8_t arr[], size_t bitno) { return (arr[bitno >> 3] >> (bitno & 7)) & 1; } static inline void set_bit (uint8_t arr[], size_t bitno, int v) { arr[bitno >> 3] = (arr[bitno >> 3] & ~(1 << (bitno & 7))) | ((v & 1) << (bitno & 7)); } 

In the get_bit() function, we shift the required bit to the low bit of the returned result.

In the set_bit() function, the changeable bit is first cleared - ~(1 << (bitno & 7)) , and then set to the specified, by shifting the low-order bit v to the desired position - (v & 1) << (bitno & 7) .