Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to specify number of bits in a byte

📅 2018-May-02 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ bit, byte, limits ⬩ 📚 Archive

In C and C++ code, I sometimes need to specify the number of bits in a byte. For example, when creating a bitset object. In old architectures, the number of bits that make a byte has varied, from 1 to 48 bits. But for all practical purposes today, 8 bits make a byte. However, I am not comfortable using the magic number 8 in my code or creating a new constant variable with that value whenever I need it.

Thankfully, the C and C++ standards have a constant for that: CHAR_BIT. It is defined in limits.h and climits. It is guaranteed to be set to the number of bits in a byte on the architecture you are running on.

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘📧