Jonas Stein
Jonas Stein

Reputation: 7043

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

Upvotes: 2

Views: 526

Answers (2)

Micha Wiedenmann
Micha Wiedenmann

Reputation: 20863

You can use the shift left operator:

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

Upvotes: 3

James
James

Reputation: 9278

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

Upvotes: 1

Related Questions