Is it possible to use bit fields as a "poor person" with a fast integer type?

I just noticed an interesting gcc property regarding bit fields. If I create a struct as follows:

 template <int N> struct C { unsigned long long data : N; }; 

Then on amd64:

  • s -m64, for N ε <1, 64>, sizeof(C) == 8 ;
  • s -m32, for N ε <1, 32>, sizeof(C) == 4 and for N ε <33, 64>, sizeof(C) == 8 .

(with sizeof(unsigned long long) == 8 ).

It looks like this is similar to C99 / C ++ 11 uint_fastXX_t , except for the fact that on my system sizeof(uint_fast8_t) == 1 . But, for example, I cannot reproduce anything like that with __int128 (which always leads to sizeof(C) == 16 ).

Does it seem to you a good idea to use the above struct as a replacement for the "poor" for uint_fastXX_t in C ++ 98?

+6
source share
2 answers

No - the bit field will often be much slower than the bare, not lost int , because if you do something (for example, addition or multiplication) that can overflow the assigned size, the compiler will (usually) insert the bitwise and command, to ensure that the result matches the specified size. For example, if you multiply two 10-bit numbers and put the result in a 10-bit field, multiplication can result in a 20-bit number, so the compiler will usually generate a 20-bit result using bitwise and to get the 10 least significant bits for the result .

+7
source

Not really. On most systems, we care about uint_fast32_t , uint_least32_t , and uint32_t will be of the same type.

In exotic equipment only, fast / least types can be 36 bits, for example, instead of 32.

+3
source

Source: https://habr.com/ru/post/923206/


All Articles