Integer logic and bit fiddling

Integer logic and bit fiddling#

Preliminaries#

Let us load the mp++ runtime, include the integer.hpp header and import the user-defined literals:

#pragma cling add_include_path("$CONDA_PREFIX/include")
#pragma cling add_library_path("$CONDA_PREFIX/lib")
#pragma cling load("mp++")

#include <mp++/integer.hpp>

using namespace mppp::literals;

Let us also include a few useful bits from the standard library:

#include <iostream>

Logic and bit fiddling#

Multiprecision integers support the standard bitwise operators, such as the bitwise NOT operator:

~(0_z1)
-1
~(123_z1)
-124

Negative integers are treated as-if they were represented using two’s complement:

~(-1_z1)
0
~(-124_z1)
123

The bitwise OR, AND and XOR operators:

std::cout << (0b01001010_z1 | 0b10010100_z1).to_string(2);
11011110
std::cout << (0b11001010_z1 & 0b10010100_z1).to_string(2);
10000000
std::cout << (0b11001010_z1 ^ 0b10010100_z1).to_string(2);
1011110

Multiprecision integer arguments can be mixed with C++ integral arguments:

std::cout << (0b01001010_z1 | 45).to_string(2);
1101111
std::cout << (-123ll & 0b10010100_z1).to_string(2);
10000100
std::cout << (255u ^ 0b10010100_z1).to_string(2);
1101011

The in-place variants are supported as well:

{
    auto n = 0b001_z1;
    n |= 0b111_z1;
    std::cout << n << '\n';
}
7
{
    int n = -0b101010;
    n &= 0b111_z1;
    std::cout << n << '\n';
}
6
{
    auto n = 0b001_z1;
    n ^= 0b111_z1;
    std::cout << n << '\n';
}
1