How can we print numbers in binary form? How can we set a bit in an integer? How we can set, clear, or toggle bits (binary digits) of a number? How can we change the nth bit of a number? In this post, we will answer these questions and use them in our own C++ software. First let’s remind ourselves where bits come from.
A brief background to CPU architecture
The construction, size, complexity, and the general form of CPUs have changed enormously since the 1950’s. On the flip side of this, the basic design and data processing technology has not changed much at all. Most CPUs today can be described as ‘Von Neumann Stored-Program Machines’. From the 1st Generation Computers with Vacuum Tubes to today’s high-end Fifth Generation Computers with Ultra Large Scale Integration (ULSI) Technology, we store and process data in two forms, ON or OFF. This smallest data or processing information is called a bit, the name is a contraction of binary digit, it represents a logical state with one of two possible values, 1 or 0. These values are most commonly represented as either ‘1’ or ‘0’, but other representations such as true/false, yes/no, +/−, or on/off are common.
The bit is the most basic unit of information in computing and digital communications. In real all operators are mainly based on Bit Operations which are also called Bitwise Operations. In computer programming, a Bitwise Operation operates on a bit string, a bit array, or a binary numeral (considered as a bit string) at the level of its individual bits, 1s, and 0s. The Bitwise Operation is basic to the higher-level arithmetic operations and it is a fast and simple action because it is directly supported by the processors. Most bitwise operations are presented as two-operand instructions where the result replaces one of the input operands.
What are the bitwise operators in C++ software?
Because of all these basics of the microarchitecture of computers, it is very important to know Bitwise Operators. The C Programming language is one of the oldest programming languages. A lot of operands, operators in other programming languages got inspiration from this language. C and C++ have the same operators and most of them are the same in other programming languages. We have explained well about operators in general in this Learn How To Use Operators In C++ post before. Now let’s see Bitwise Operators.
Using Bits in C++ software
How do we print numbers in binary form?
We can print integer numbers as in 8bits or 16bits sets as below,
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <bitset> int main() { unsigned int a = 65, b = 255, c = 128; std::cout << "a = " << std::bitset<8>(a) << '\n'; std::cout << "b = " << std::bitset<8>(b) << '\n'; std::cout << "c = " << std::bitset<16>(c) << '\n'; } |
How do we set a Binary String from an Integer?
We can set string from an integer as below,
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <bitset> int main() { std::string binary = std::bitset<8>(128).to_string(); //to binary std::cout<<binary<<"\n"; getchar(); return 0; } |
How do we create an Integer from a Binary string representation?
We can set string from an integer as below,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <iostream> #include <bitset> int main() { std::string binary = "10011001"; unsigned long decimal = std::bitset<8>(binary).to_ulong(); std::cout << decimal << '\n'; getchar(); return 0; } |
How do we set a bit?
We can set a nth bit of a number as below,
1 2 3 |
number |= 1UL << n; |
This will set the n
th bit of number
. n
should be zero, if we want to set the 1
st bit and so on up to n-1
, if you want to set the n
th bit. We can use 1ULL
if number
is wider than unsigned long
; promotion of 1UL << n
doesn’t happen until after evaluating 1UL << n
where it’s undefined behavior to shift by more than the width of a long
.
How do we set the nth bit of a number to x?
It is good to use unsigned types for portable bit manipulations. We can change bits of a number as below,
1 2 3 |
number = (number & ~(1UL << n)) | (x << n); |
We can make independent of 2’s complement negation behavior (where -1
has all bits set, unlike on a 1’s complement or sign/magnitude C++ implementation), use unsigned negation.
1 2 3 |
number ^= (-(unsigned long)x ^ number) & (1UL << n); |
1 2 3 4 |
unsigned long newbit = !!x; // Lets booleanize to force 0 or 1 number ^= (-newbit ^ number) & (1UL << n); |
We can set the n
th bit to either 1
or 0
can be achieved with the following on a 2’s complement C++ implementation.
1 2 3 |
number ^= (-x ^ number) & (1UL << n); |
Here bit n
will be set if x
is 1
, and cleared if x
is 0
. If x
has some other value, we will be garbage. In previous example x = !!x
will booleanize it to 0 or 1.
We can use preprocessor macros (i.e. the community wiki answer further down) or some sort of encapsulation methods can be also used to change bits.
We can also use The Boost Version, this will allow a runtime sized bitset compared with a standard library compile-time sized bitset.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <iostream> #include <bitset> int main() { std::bitset<8> x; x[0] = 0; x[1] = 1; x[2] = 0; x[3] = 0; x[4] = 0; x[5] = 0; x[6] = 1; x[7] = 1; std::cout << x << std::endl; getchar(); return 0; } |
The output will be “11000010”
How do we clear a bit in our C++ software app?
We can use the bitwise AND operator (&
) to clear a bit. We can clear a bit as below,
1 2 3 |
number &= ~(1UL << n); |
This will clear the n
th bit of number
. We should invert the bit string with the bitwise NOT operator (~
), then AND it.
How do we check a bit in C++?
We can check a bit, by shifting the number n to the right, then bitwise AND it. We can set a bit from an integer or check bits of an integer as below,
1 2 3 |
bit = (number >> n) & 1U; |
This will set the value of the n
th bit of number
into the variable bit
.
How do we toggle a bit in C++ software?
We can use the XOR operator (^
) can be used to toggle a bit. We can toggle bits of sets as below,
1 2 3 |
number ^= 1UL << n; |
This will toggle the n
th bit of number
.
Please see our Bitwise Operations in C++ post about AND, OR, XOR, NOT and Shifting operators.
Design. Code. Compile. Deploy.
Start Free Trial
Free C++Builder Community Edition