Jun Li
Jun Li

Reputation: 33

Fast integer power of two

I can't understand these codes for fast integer power of two,

inline constexpr std::uint64_t pow2 (std::uint64_t i)
{
    return std::uint64_t(1) << i;
}

In fact, I can't understand how following codes work, uint64_t is just a type, int is also OK,

return std::uint64_t(1) << i;

Upvotes: 1

Views: 4655

Answers (3)

Dakusan
Dakusan

Reputation: 6691

The << is the bit shift operator, which essentially multiplies a number by 2 for every 1 in the number.

so 1<<2 = 1*2*2

3<<5= 3*2*2*2*2*2

And multiplying by 2 for each 1 in the number is just raising 2 to a power and multiplying by the original value. (Thanks for the correction M.M)

Upvotes: 2

Peter
Peter

Reputation: 36597

type(x) in C++ is simply an alternative to the C type conversion (type)x.

So std::uint64_t(1) is equivalent to (std::uint64_t)1 and produces a std::uint64_t with value 1. (Note: std::uint64_t is C++11 or later).

For unsigned integral types, the standard also specifies that left shift n is equivalent to multiplying by 2, n times (i.e. multiplying by 2 to the power of n), as long as overflow of the type does not occur.

For signed types, the result of left shift is not defined for negative values.

Upvotes: 3

sashang
sashang

Reputation: 12194

It's just calling the constructor of unit64_t. You don't normally see it used with basic types like that. Normally constructors are used with user defined classes and one might see something like:

return A(1);

where A is a class defined by the user.

In this case substitute A with std::uint64_t. Then the << multiplies the value 1 by 2 an i number of times.

Upvotes: 0

Related Questions