Algorithms_in_C++ 1.0.0
Set of algorithms implemented in C++.
Loading...
Searching...
No Matches
bit_manipulation Namespace Reference

for IO operations 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 IO operations

Bit manipulation algorithms.

for io operations

Program to generate n-bit Gray code

storing the numbers

for assert

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 assert

Bit Manipulation algorithms

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

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

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