Search code examples
c++binarycoding-styleconstantscode-readability

How to use constant powers of 2 readable in c++?


I need several integer constants with 2^n and 2^n - 1 in my GNU c++ code.

What is a good practise to keep the code readable? The code uses decimal values at the moment 4294967296 and 65536 which is hard to debug in future.

2^12 is not implemented in standard C++ and pow(2.0,12.0) uses double.

if (buffer_length == 4294967295){ } // code example, I want to make more readable

Solution

  • You can use the shift left operator:

    if (buffer_length == 1 << 12){ }