Bit Operations

You will learn about bit operations in D in this lesson.

After going over how values are represented by bits and how numbers are represented in binary and hexadecimal, you can now see operations that change values at bit-level.

Because there is no direct access to individual bits, even though these operations are at bit-level, they affect at least 8 bits at a time. For example, for a variable of type ubyte, a bit operation would be applied to all of the 8 bits of that variable.

As the uppermost bit is the sign bit for signed types, we will ignore signed types and use only uint in the examples below. You can repeat these operations with ubyte, ushort, and ulong; as well as byte, short, int, and long, as long as you remember the special meaning of the uppermost bit.

First, let’s define a function that will be useful later when examining how bit operators work. This function will print a value in binary, hexadecimal, and decimal systems:

Press + to interact
import std.stdio;
void print(uint number) {
writefln(" %032b %08x %10s", number, number, number);
}
void main() {
print(123456789);
}

Here is the same value printed in the binary, hexadecimal, and decimal number systems:

00000111010110111100110100010101 075bcd15  123456789

Complement operator: ~

Not to be confused with the binary ~ operator that is used for array concatenation, this is the unary ~ operator.

This ...