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

328 views Asked by At

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
2

There are 2 answers

4
Micha Wiedenmann On BEST ANSWER

You can use the shift left operator:

if (buffer_length == 1 << 12){ } 
3
James On

Use hex. It should be pretty easy for anyone to figure out that it's a special number.