TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
bit_manipulation Namespace Reference

for assert More...

Functions

uint64_t next_higher_number (uint64_t x)
 The main function implements checking the next number.
 
bool isPowerOfTwo (std ::int64_t n)
 The main function implements check for power of 2.
 

Detailed Description

for assert

Program to generate n-bit Gray code

storing the numbers

for IO operations

Bit manipulation algorithms

for assert for IO operations

Bit manipulation algorithms

Gray code is a binary numeral system where consecutive values differ in exactly 1 bit. The following code offers one of many possible Gray codes given some pre-determined number of bits. for gray code representation for assert for IO operations for vector data structure

Bit manipulation algorithms

for io operations

Bit Manipulation algorithms

for std::min for IO operations for limits of integral types for std::vector

Bit manipulation algorithms

Function Documentation

◆ isPowerOfTwo()

bool bit_manipulation::isPowerOfTwo ( std ::int64_t n)

The main function implements check for power of 2.

Parameters
nis the number who will be checked
Returns
either true or false

Definition at line 32 of file power_of_2.cpp.

32 { // int64_t is preferred over int so that
33 // no Overflow can be there.
34
35 return n > 0 && !(n & n - 1); // If we subtract a power of 2 numbers by 1
36 // then all unset bits after the only set bit become set; and the set bit
37 // becomes unset.
38
39 // If a number n is a power of 2 then bitwise and of n-1 and n will be zero.
40 // The expression n&(n-1) will not work when n is 0.
41 // To handle this case also, our expression will become n& (!n&(n-1))
42}

◆ next_higher_number()

uint64_t bit_manipulation::next_higher_number ( uint64_t x)

The main function implements checking the next number.

Parameters
xthe number that will be calculated
Returns
a number

Definition at line 33 of file next_higher_number_with_same_number_of_set_bits.cpp.

33 {
34 uint64_t rightOne = 0;
35 uint64_t nextHigherOneBit = 0;
36 uint64_t rightOnesPattern = 0;
37
38 uint64_t next = 0;
39
40 if (x) {
41 // right most set bit
42 rightOne = x & -static_cast<signed>(x);
43
44 // reset the pattern and set next higher bit
45 // left part of x will be here
46 nextHigherOneBit = x + rightOne;
47
48 // nextHigherOneBit is now part [D] of the above explanation.
49
50 // isolate the pattern
51 rightOnesPattern = x ^ nextHigherOneBit;
52
53 // right adjust pattern
54 rightOnesPattern = (rightOnesPattern) / rightOne;
55
56 // correction factor
57 rightOnesPattern >>= 2;
58
59 // rightOnesPattern is now part [A] of the above explanation.
60
61 // integrate new pattern (Add [D] and [A])
62 next = nextHigherOneBit | rightOnesPattern;
63 }
64
65 return next;
66}