CS102: Number Systems and Bitwise Operators
Positional Number Systems:
Positional number systems represent a number and its magnitude, using the “position” as a digit to be placed
The Power bases:
Decimal: 10^p
Binary (Twos): 2^p
Hexadecimal: 16^p
Octal: 8^p
Place starts with the power (p) = 0 (similar to the array index)
Base has digits 0 to (base - 1)
Decimal: 0 to 9
Binary: 0 to 1
Hexadecimal: 0 to 9, then A to F
Octal: 0 to 7
An introduction to Binary Numbers
Composed of 0 and 1 to replicate “on” and “off”
Converting from Binary to Decimal
While decimal values contain places such as a ones, tens, hundreds, thousands, etc. and then tenths, hundredths, and thousandths.
Binary numbers have corresponding decimal places, except they are represented as powers of 2.
Ex. For the binary [1 1 0 1 . 1 1]
1(2³) + 1(2²) + 0(2^1) + 1(2^0) + 1(2^-1) + 1(2^-2) = 13.75
Converting from Decimal to Binary:
Bitwise Operators:
The Logical And(&) Operator:
The binary AND operator, represented as in C++ and similar languages, is a bitwise operation that compares corresponding bits of two numbers. It returns a new number where each bit is set to 1 only if both of the corresponding bits in the operands are also 1. Otherwise, the resulting bit is 0.
Examples:
Performing a bitwise AND operation:
0110 (6) & 1010 (10) = 0010 (2)
The AND operator is commonly used for:
Masking bits: Extracting specific bits from a number by combining it with a "mask."
Testing individual bits: To check if a particular bit is set to 1.
Logical operations at the binary level.
Here's a practical example in C++ that demonstrates how to use the binary AND (&) operator to extract specific bits from a number:
#include <iostream>
using namespace std;
int main() {
int num = 42; // Binary: 0010 1010
int mask = 8; // Binary: 0000 1000
// Perform a bitwise AND
int result = num & mask; //0010 1010 (42) & 0000 1000 (8) = 0100 1000 (8)
cout << "Number: " << num << endl; // Prints 42
cout << "Mask: " << mask << endl; // Prints 8
cout << "Result: " << result << endl; // Prints 8
// Check if a particular bit is set
if (result != 0) {
cout << "The 4th bit is set!" << endl;
} else {
cout << "The 4th bit is NOT set!" << endl;
}
return 0;
}Explanation:
num is the number we're working with (42, which is 0010_1010 in binary).
mask is the binary mask (8, which is 0000_1000 in binary). It isolates the 4th bit
num & mask compares each bit in num and mask.
Since only the 4th bit in each set is “1”, the output is “8”
When you run this program, it checks if the 4th bit in is set (1) and prints the result.
The Logival Or (|) Operator:
The binary OR operator, represented by the (|) symbol in C++, performs a bitwise operation between two numbers. It compares each bit of the operands and returns a new number where each bit is set to 1 if either of the corresponding bits in the operands is 1. If both bits are 0, the result is 0.
Example
Let's take two binary numbers:
0110 (6) | 1010 (10) = 1110 (14)
Use Cases
The OR operator is useful for:
Setting bits: Turning specific bits on (setting them to 1).
Combining binary values: Merging two sets of binary data.
Logical operations: At the bit level.
Here's a practical example in C++ that demonstrates how to use the binary OR (|) operator:
#include <iostream>
using namespace std;
int main() {
int num1 = 6; // Binary: 0000 0110
int num2 = 10; // Binary: 0000 1010
// Perform a bitwise OR
int result = num1 | num2; // 0000 0110 (6) | 0000 1010 (10) = 0000 1110 (14)
cout << "Number 1: " << num1 << endl; // Prints 6
cout << "Number 2: " << num2 << endl; // Prints 10
cout << "Result: " << result << endl; // Prints 14
return 0;
}Explanation:
num1 is 6 in binary (0110), and num2 is 10 in binary (1010)
the operation num1 | num2 compares corresponding bits from both numbers, and sets each bit to 1 if either bit is 1.
The result is 1110 in binary, which equates 14 in decimal.
When you run this program, it will display the result of the OR operation between the two numbers.
The Logical XOr (^) Operator:
The binary XOR operator, represented as in C++, stands for "exclusive OR." It compares corresponding bits of two numbers and returns a new number where each bit is set to 1 if the bits in the operands are different. If the bits are the same, the resulting bit is 0.
Example
Performing a bitwise XOR operation:
0110 (6) ^ 1010 (10) = 1100 (12)
Key Point:
If both bit-sets have corresponding values (both 0 or both 1): The result is “0”
If not: The result is “1”
Use cases:
The XOR operator is commonly used for:
Swapping values without using a temporary variable.
Cryptography, like simple encryption techniques (e.g., XOR cipher).
Bit toggling, to flip specific bits of a number.
Here’s an example in C++ that demonstrates the binary XOR () operator in action:
#include <iostream>
using namespace std;
int main() {
int num1 = 6; // Binary: 0000 0110
int num2 = 10; // Binary: 0000 1010
// Perform a bitwise XOR
int result = num1 ^ num2; // 0000 0110 (6) ^ 0000 1010 (10) = 0000 1100 (12)
cout << "Number 1: " << num1 << endl; // Prints 6
cout << "Number 2: " << num2 << endl; // Prints 10
cout << "Result: " << result << endl; // Prints 12
return 0;
}Explanation:
Compares the two bit sets and outputs “0” for different bits, and “1” for corresponding bits.
The Logical Not (~) Operator:
The binary NOT operator, represented as (~) in C++, is a bitwise complement operator. It flips every bit of a number: 1 becomes 0, and 0 becomes 1. Essentially, it inverts the binary representation of a number.
Applying the NOT operator:
~0000 0101 (5) = 1111 1010 (-6)
Key Point:
NOT flips bits: Operates at the binary level to invert every bit.
Signed Numbers: For signed integers, the NOT operator affects the sign due to how negative numbers are stored (using two's complement).
Use cases:
Generating complements for calculations.
Quickly inverting bit patterns, useful in low-level programming and cryptography.
Here's an example in C++ that demonstrates how to use the binary NOT (~) operator:
#include <iostream>
using namespace std;
int main() {
int num = 5; // Binary: 00000101 (in 8-bit representation)
// Perform the NOT operation
int result = ~num;
cout << "Number: " << num << endl; // Prints 5
cout << "Result: " << result << endl; // Prints -6 (two's complement representation)
return 0;
}Explanation:
The number 5 is represented in binary as 0000 0101.
Applying the NOT (~) operator inverts each bit, resulting in 1111 1010, this is the binary representation of (-6)
The program outputs the original number (5) and the result of the NOT (~) operator (6).
The behavior of the NOT operator is tied to two's complement encoding, which is used for signed integers in most programming systems.
The Logical Left-Shift («) Operator:
The Logical Left Shift («) is a signed agnostic binary operator.
ex. (value) « (number of shifts)
Bits which fall off of the left are discarded
0’s are added from the right
Mathematically: (value) * 2 ^ (number of shfts)
ex. 0b 0100 1001 (73) « 2 = 0b 0010 0100 (36)
Digits in the 2^8 and 2^7 place are truncated
The Logical Right-Shift (») Operator:
The Artihmetic right shift is a signed agnostic binary operator.
Ex. (unsigned value) » (number of shifts)
Bits which fall off of the right are discarded
0’s are added from the left
Mathermatically: (unsigned value) / 2 ^ (number of shifts)
Ex. 0b 0010 1001 (42) » 2 = 0b 0001 0010 (18)
The Arithmetic Right-Shift (») Operator:
Very similar to the Logical right shift operator, but the signed value affects if 0’s or 1’s are added to the left.
ex. 0b 1100 1001 (-73) » 2 = 0b 1111 0010 (-112)
Enumeration (enum):
In C++, an (short for "enumeration") is a user-defined data type that consists of a set of named integral constants. It's useful when you have a variable that can only take on a limited set of predefined values (8). By using an , you can improve the readability and maintainability of your code.
Here’s an example to illustrate:
#include <iostream>
using namespace std;
// Define an enum for days of the week
enum DayOfWeek {//Can only hold 8 elements, all unassigned elements are left empty
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
};
int main() {
DayOfWeek today = Wednesday;
if (today == Wednesday) {
cout << "It's midweek!" << endl;
}
return 0;
}Features of Enumeration:
Assigns an index to each element in the enumeration
These values can be modified.
enum Color { Red = 1, Green = 3, Blue = 5 };Type Safety: Enums add type safety by restricting the possible values a variable can take, reducing bugs caused by invalid values.
Scope: Enums are part of the enclosing namespace or class scope. If you need the enumeration values to be confined to the enum itself, consider using enum class introduced in C++11.
Byte Mask:
In C++, a byte mask is a pattern of bits (usually represented as a sequence of s and s) used for bitwise operations. It helps extract, modify, or check specific bits within a byte (or larger data types). Byte masks are often combined with bitwise operators like (AND), (OR), (XOR), and (NOT) to manipulate individual bits.
Here's an example to clarify the concept:
Use Case: Extracting Specific Bits
Let's say you have a byte (8 bits), and you want to extract the lower 4 bits (the least significant bits).
#include <iostream>
using namespace std;
int main() {
uint8_t byte = 0b10101111; // A byte with binary value: 10101111
uint8_t mask = 0b00001111; // Mask to isolate the lower 4 bits
uint8_t result = byte & mask; // Perform bitwise AND to extract the lower 4 bits
cout << "Original byte: 0b" << bitset<8>(byte) << endl;
cout << "Masked result: 0b" << bitset<8>(result) << endl;
return 0;
}
//Original byte: 0b10101111
//Masked result: 0b00001111Key Bitwise Operations with Masks:
Extracting Bits: Use the AND(&) Binary Modifier to retain only the bits specified in the mask.
uint8_t extracted = value & mask;Setting Bits: Use the OR(|) Binary Modifier to turn on specific bits without altering others.
uint8_t updated = value | mask;Toggling Bits: Use the XOR(^) Binary Modifier to flip specific bits
uint8_t toggled = value ^ mask;Clearing Bits: Use AND(&) and NOT(~) Binary Modifiers with the complement of a mask () to turn off specific bits
uint8_t cleared = value & ~mask;Practical Applications:
Flags: Using specific bits to store boolean flags.
Hardware Control: Manipulating control registers in embedded systems.
Data Packing: Encoding multiple values into a single byte.
Unsigned and Signed Integer values: (INCOMPLETE)
In C++, signed and unsigned integers are variations of data types that define the range of values an integer can store.
Signed Integers
A signed integer can represent both positive and negative values. By default, most integer types are signed in C++.
For example:
int a = -10; // A signed integer can store negative values.A signed integer uses one bit to indicate the sign (positive or negative), leaving the remaining bits for the value itself. For instance:
An 8-bit signed integer can store values from -128 to 127.
Unsigned Integers
An unsigned integer can only represent non-negative values (positive integers and zero). This allows unsigned integers to hold a larger range of positive values since no bit is used for a sign.
For example:
size_t b = 10; // An unsigned integer cannot store negative values.Why Choose One Over the Other?
Signed integers are ideal when negative numbers need to be represented, such as in temperature calculations.
Unsigned integers are useful when values are strictly non-negative, such as for array indices, counters, or memory addresses.
Using int and size_t:
int:
Represents a signed integer, capable of storing both positive and negative values.
Commonly used for mathematical operations, counters, or general-purpose integer variables.
size_t:
Is an unsigned integer type specifically designed to represent sizes and indexes in memory-related contexts (such as array indexing or the size of objects).
It guarantees sufficient range to hold any possible object size or array index on the target platform (hence, it’s unsigned).
size_t size = sizeof(int); // Size of an int in bytes
Key Difference:
The int type is not inherently "assigned" and size_t is not exclusively "unassigned." The distinction lies in their intended purposes:
int is versatile and widely applicable to general scenarios where you need signed integers.
size_t is optimized for memory-related operations and ensures no negative value (like array indices).
Two’s Complement:
In two's complement:
The most significant bit (MSB) is the sign bit: 0 for positive numbers and 1 for negative numbers.
Negative numbers are represented by taking the two's complement of their positive counterparts (invert the bits and add 1).
This system ensures that arithmetic operations like addition and subtraction work seamlessly with both positive and negative numbers.
Binary Representation of (-1):
For an (-1) signed integer, (-1) has a special property: All its bits are set to 1. For example:
In 8-bits: 1111 1111
in 16-bits: 1111 1111 1111 1111
This happens because:
If we start with the binary representation of 1 (0000 0001)
Then invert the bits (using the (~)Not operator) (1111 1110)
Then add 1 (1111 1111)
Example (2’s Complement): Writing (-)30 in binary form to (+)30 in decimal form
int main () {
int num = 30;
int negativeNum = (~num + 1);
}
//The not operator is used to flip the binary values of 30 (from 0001 1110 to 1110 0001), then one is added to change the sign in the 2^7 element from 1 to 0 (1110 0001 to 0110 0001)Hexadecimals:
In C++, hexadecimals (often abbreviated as "hex") are a base-16 numbering system. Unlike the decimal system (base-10), which uses digits 0–9, hexadecimals use 16 symbols: digits 0–9 and letters A–F, where:
A represents 10
B represents 11
C represents 12
D represents 13
E represents 14
F represents 15
G represents 16
So, a hexadecimal looks like: 1234 5678 9ABC DEFG
Why Use Hexadecimals?
Hexadecimals are widely used in programming because they provide a compact and human-readable way to represent binary values. One hexadecimal digit represents exactly 4 bits (a nibble), so:
Two hexadecimal digits represent 1 byte (8 bits).
This makes hex ideal for representing memory addresses, color codes, or binary data.
Writing Hexadecimals in C++
To specify a hexadecimal value in C++, you prepend it with 0x or 0X.
For example:
int hexValue = 0x1A; // Hexadecimal representation of 26 in decimalOutputting Hexadecimals
C++ provides ways to input or output hexadecimal values using standard I/O.
For Example:
#include <iostream>
using namespace std;
int main() {
int hexValue = 0x1A;
cout << "Decimal: " << hexValue << endl; // Output: Decimal: 26
cout << "Hexadecimal: " << hex << hexValue << endl; // Output:
Hexadecimal: 1a
return 0;
}Here, the hex manipulator ensures that the number is displayed in hexadecimal format.
Conversion Between Decimal and Hexadecimal
Decimal to Hex: Divide the decimal number by 16 repeatedly and record the remainders (in reverse order).
Hex to Decimal: Multiply each hex digit by 16 raised to the power of its position (from right to left, starting at 0).