Converting Values#
Converting between different numerical and data representations is an essential skill in programming, allowing for efficient data processing, interoperability, and the ability to build versatile applications. This guide will explore how to validate, convert, encode, and decode various formats, making your programs both robust and flexible. These concepts also serve as a foundation for implementing more complex systems in SplashKit, such as cryptographic utilities or network tools.
Validation Functions#
Validation is the first step in any reliable conversion process. Ensuring input values conform to their respective formats reduces errors and creates a solid foundation for processing data. For example, binary numbers must consist only of 0
s and 1
s, while hexadecimal values use a combination of numeric and alphabetic characters. In this section, we’ll explore how to check the correctness of binary, decimal, hexadecimal, and octal values, ensuring all inputs are clean and error-free before proceeding with conversions.
Handy Tip
The following validation functions are used in the conversion operations described later in this guide. They check whether a given string is a valid representation of a binary, decimal, hexadecimal, or octal number, respectively.
Is Binary#
This function checks if a given string is a valid binary number, ensuring it contains only the characters 0
and 1
. It also verifies that the input is not empty, returning false for any invalid or empty input.
def is_binary(binary_string):
return all(character in '01' for character in binary_string) and bool(binary_string)
We can use this function within many other functions, or even to just check if a string is a binary number:
binary_string1 = "1003300101"
print(F"Value {binary_string1} is a {is_binary(binary_string1)} binary value")
binary_string2 = "10010101"
print(F"Value {binary_string2} is a {is_binary(binary_string2)} binary value")
Value 1003300101 is a False binary value
Value 10010101 is a True binary value
Is Hexadecimal#
This function validates whether a string represents a valid hexadecimal number. It checks that each character falls within the ranges 0-9
, A-F
, or a-f
, while also ensuring the input is not empty.
def is_hex(hex_string):
return all(character in '0123456789ABCDEFabcdef' for character in hex_string) and bool(hex_string)
We can use this function to verify hexadecimal strings before converting them to other formats:
hex_string1 = "1A2B3C4D5F"
print(f"Value {hex_string1} is a {is_hex(hex_string1)} hex value") # True
hex_string2 = "1A2B3C4D5G"
print(f"Value {hex_string2} is a {is_hex(hex_string2)} hex value") # False
Value 1A2B3C4D5F is a True hex value
Value 1A2B3C4D5G is a False hex value
Is Octal#
This function determines if a string is a valid octal number by ensuring all characters are within the range 0-7
. It also returns false if the input string is empty.
def is_octal(octal_string):
return all(character in '01234567' for character in octal_string) and bool(octal_string)
We can use this function to validate octal strings before converting them to other formats:
octal_string1 = "1234567"
print(f"Value {octal_string1} is a {is_octal(octal_string1)} octal value") # True
octal_string2 = "12345678"
print(f"Value {octal_string2} is a {is_octal(octal_string2)} octal value") # False
Value 1234567 is a True octal value
Value 12345678 is a False octal value
Basic Conversion Operations#
Conversions between number systems are fundamental to understanding how data is represented in programming. Whether you’re transforming binary to decimal, decimal to hexadecimal, or even converting between less common systems like octal and base-64, these operations provide insight into the underlying mechanics of data storage and manipulation. This section will introduce methods for performing these conversions step by step, helping you understand the relationships between different numerical systems and how to implement them efficiently in code.
Decimal to Binary#
The conversion of a decimal number to binary involves repeatedly dividing the decimal number by 2 and storing the remainders. These remainders, when read in reverse order, represent the binary equivalent of the decimal number. This method ensures an efficient step-by-step breakdown of the decimal number into its binary representation. For example, the decimal number 10 is converted to binary by dividing it by 2 until the quotient is 0, collecting the remainders along the way.
Algorithm 1 (Decimal to Binary Conversion)
Input: A decimal integer \(N\)
Output: Binary representation of \(N\)
Represent the binary equivalent of \(N\) as the sum of powers of 2:
\[ N = \sum_{i=0}^k b_i \cdot 2^i \]where \(b_i \in \{0, 1\}\) and \(k\) is the highest power of 2 less than or equal to \(N\).
Extract the binary digits \(b_i\) iteratively:
Compute \(b_0\) as \(N \mod 2\), which gives the remainder when \(N\) is divided by 2.
Update \(N\) by performing integer division:
\[ N \gets \lfloor N / 2 \rfloor \]Repeat this process until \(N = 0\).
Collect the binary digits \(b_0, b_1, \ldots, b_k\) in reverse order.
Reverse the order of the collected binary digits to obtain the correct binary representation:
\[ B = b_k b_{k-1} \ldots b_1 b_0 \]Return \(B\).
Example of Decimal to Binary Conversion
Consider the decimal number \(10\). We convert it to binary using the algorithm:
Initial Number (\(N = 10\))
Compute the remainder: \(10 \mod 2 = 0\)
Quotient: \(10 \div 2 = 5\) (integer division)
Store \(0\) in
binary_digits
.
Next Number (\(N = 5\))
Compute the remainder: \(5 \mod 2 = 1\)
Quotient: \(5 \div 2 = 2\)
Store \(1\) in
binary_digits
.
Next Number (\(N = 2\))
Compute the remainder: \(2 \mod 2 = 0\)
Quotient: \(2 \div 2 = 1\)
Store \(0\) in
binary_digits
.
Next Number (\(N = 1\))
Compute the remainder: \(1 \mod 2 = 1\)
Quotient: \(1 \div 2 = 0\)
Store \(1\) in
binary_digits
.
Reversing and Combining the Digits
binary_digits
(in reverse order of computation): \([0, 1, 0, 1]\).Reverse the digits to obtain \([1, 0, 1, 0]\).
Join the digits to form the binary number \(1010\).
Final Result: The binary representation of \(10\) is \(1010\).
def dec_to_bin(decimal_value):
if decimal_value == 0:
return "0"
binary_string = ""
while decimal_value > 0:
binary_string = ("1" if decimal_value & 1 else "0") + binary_string
decimal_value >>= 1
return binary_string
decimal_value = 10
binary_string = dec_to_bin(decimal_value)
print("Binary value:", binary_string)
Binary value: 1010
If we change the input value to \(22\), the output will be:
decimal_value = 22
binary_string = dec_to_bin(decimal_value)
print("Binary value:", binary_string)
Binary value: 10110
Binary to Decimal#
The conversion of a binary number to decimal involves summing up each binary digit multiplied by \(2^n\), where \(n\) represents the position of the digit from the rightmost bit (starting at 0). This method provides a straightforward way to compute the decimal value of a binary number. For example, the binary number \(1010\) is converted to decimal by calculating the weighted sum of its digits.
Algorithm 2 (Binary to Decimal Conversion)
Input: A binary string \(B\)
Output: Decimal representation of \(B\)
Represent the binary string \(B\) as \(b_k b_{k-1} \ldots b_1 b_0\), where \(b_i \in \{0, 1\}\) and \(k\) is the index of the most significant bit (MSB).
Initialise the decimal number \(D = 0\).
Compute the decimal equivalent:
\[ D = \sum_{i=0}^k b_i \cdot 2^i \]For each binary digit \(b_i\), its value contributes \(b_i \cdot 2^i\) to the sum, where \(i\) is the position of the digit from right to left (with \(i = 0\) for the least significant bit).
Return \(D\).
Example of Binary to Decimal Conversion
Consider the binary number \(1010\). We convert it to decimal using the algorithm:
Binary Number: \(1010\) (read left to right)
Most Significant Bit (MSB):
\(1 \times 2^3 = 8\)Next Bit:
\(0 \times 2^2 = 0\)Next Bit:
\(1 \times 2^1 = 2\)Least Significant Bit (LSB):
\(0 \times 2^0 = 0\)
Summing the Results:
\(8 + 0 + 2 + 0 = 10\)
Final Result: The decimal representation of \(1010\) is \(10\).
def bin_to_dec(binary_string):
if not is_binary(binary_string):
return 0
decimal_value = 0
for i, character in enumerate(reversed(binary_string)):
if character == '1':
decimal_value += (1 << i)
return decimal_value
binary_string = "1010"
decimal_value = bin_to_dec(binary_string)
print("Decimal value:", decimal_value)
Decimal value: 10
If we change the input value to \(10110\), the output will be:
binary_string = "10110"
decimal_value = bin_to_dec(binary_string)
print("Decimal value:", decimal_value)
Decimal value: 22
Hexadecimal to Binary#
The conversion of a hexadecimal number to binary involves translating each hexadecimal digit into its 4-bit binary equivalent. This method ensures an efficient and accurate conversion process, as each hexadecimal digit directly maps to a fixed binary sequence. For example, the hexadecimal number \(A3\) is converted to binary by mapping \(A\) to \(1010\) and \(3\) to \(0011\), resulting in \(10100011\).
Algorithm 3 (Hexadecimal to Binary Conversion)
Input: A hexadecimal string \(H\)
Output: Binary representation of \(H\)
Represent each hexadecimal digit \(h\) as a 4-bit binary string using a mapping:
\[ h \in \{0, 1, \dots, 9, A, B, C, D, E, F\} \quad \to \quad \text{4-bit binary equivalent.} \]Example mapping:
\[ \{'0': '0000', '1': '0001', \dots, 'A': '1010', \dots, 'F': '1111'\}. \]Let the binary result \(B\) be an empty string.
For each digit \(h\) in \(H\):
\[ B \gets B \, || \, \text{binary equivalent of } h \]Here, \(||\) denotes concatenation of strings.
Return \(B\).
Example of Hexadecimal to Binary Conversion
Consider the hexadecimal number \(A3\). We convert it to binary using the algorithm:
Hexadecimal Number: \(A3\)
First Digit (\(A\)):
Using the mapping \(A \to 1010\), store \(1010\).Second Digit (\(3\)):
Using the mapping \(3 \to 0011\), store \(0011\).
Combine the Binary Equivalents:
Concatenate \(1010\) and \(0011\) to form \(10100011\).
Final Result: The binary representation of \(A3\) is \(10100011\).
def hex_to_bin(hex_string):
if not is_hex(hex_string):
return ""
binary_string = ""
for hex_character in hex_string:
hex_value = int(hex_character, 16)
for i in range(3, -1, -1):
binary_string += "1" if (hex_value >> i) & 1 else "0"
if len(hex_string) == 1:
first_one = binary_string.find('1')
return "0" if first_one == -1 else binary_string[first_one:]
return binary_string
hex_string = "A3"
binary_string = hex_to_bin(hex_string)
print("Binary value:", binary_string)
Binary value: 10100011
If we change the input value to \(FA\), the output will be:
hex_string = "FA"
binary_string = hex_to_bin(hex_string)
print("Binary value:", binary_string)
Binary value: 11111010
Binary to Hexadecimal#
The conversion of a binary number to hexadecimal involves grouping the binary digits into sets of four bits (starting from the rightmost bit) and then mapping each group to its hexadecimal equivalent. This method ensures a straightforward translation between binary and hexadecimal systems, as four binary digits correspond to one hexadecimal digit. For example, the binary number \(10100011\) is grouped as \(1010\) and \(0011\), which map to the hexadecimal digits \(A\) and \(3\), resulting in \(A3\).
Algorithm 4 (Binary to Hexadecimal Conversion)
Input: A binary string \(B\)
Output: Hexadecimal representation of \(B\)
Represent each 4-bit binary group \(b\) as a single hexadecimal digit using a mapping:
\[ b \in \{0000, 0001, \dots, 1110, 1111\} \quad \to \quad \text{hexadecimal equivalent.} \]Example mapping:
\[ \{'0000': '0', '0001': '1', \dots, '1010': 'A', \dots, '1111': 'F'\}. \]If the length of \(B\) is not a multiple of 4, pad \(B\) with leading zeros until its length is divisible by 4:
\[ B \gets \text{'0'}^{m} || B, \quad m = 4 - (\text{length of } B \mod 4). \]Let the hexadecimal result \(H\) be an empty string.
Divide \(B\) into 4-bit groups:
\[ B = b_k || b_{k-1} || \ldots || b_1 || b_0, \quad \text{where each } b_i \text{ is a 4-bit group.} \]For each 4-bit group \(b_i\):
\[ H \gets H \, || \, \text{hexadecimal equivalent of } b_i \]Here, \(||\) denotes concatenation of strings.
Return \(H\).
Example of Binary to Hexadecimal Conversion
Consider the binary number \(10100011\). We convert it to hexadecimal using the algorithm:
Binary Number: \(10100011\)
Group the Binary Digits:
Divide the binary number into groups of four bits from right to left:
\(1010\), \(0011\).
Map Each Group to its Hexadecimal Equivalent:
\(1010 \to A\)
\(0011 \to 3\)
Combine the Hexadecimal Digits:
Concatenate \(A\) and \(3\) to form \(A3\).
Final Result: The hexadecimal representation of \(10100011\) is \(A3\).
def bin_to_hex(binary_string):
if not is_binary(binary_string):
return ""
length = len(binary_string)
padding = (4 - (length % 4)) % 4
padded_binary_string = "0" * padding + binary_string
hex_string = ""
for i in range(0, len(padded_binary_string), 4):
hex_value = int(padded_binary_string[i:i+4], 2)
hex_string += hex(hex_value)[2:].upper()
return hex_string
binary_string = "10100011"
hex_string = bin_to_hex(binary_string)
print("Hexadecimal value:", hex_string)
Hexadecimal value: A3
If we change the input value to \(1100101011\), the output will be:
binary_string = "1100101011"
hex_string = bin_to_hex(binary_string)
print("Hexadecimal value:", hex_string)
Hexadecimal value: 32B
Decimal to Octal#
The conversion of a decimal number to octal involves repeatedly dividing the number by \(8\) and recording the remainder at each step. These remainders, when read in reverse order, form the octal representation of the decimal number. For example, the decimal number \(10\) is converted to octal by dividing it by \(8\) until the quotient is \(0\), and then reading the remainders from bottom to top.
Algorithm 5 (Decimal to Octal Conversion)
Input: A decimal integer \(N\)
Output: Octal representation of \(N\)
Represent the octal equivalent of \(N\) as the sum of powers of 8:
\[ N = \sum_{i=0}^k d_i \cdot 8^i \]where \(d_i \in \{0, 1, \dots, 7\}\) and \(k\) is the highest power of 8 less than or equal to \(N\).
Extract the octal digits \(d_i\) iteratively:
Compute \(d_0\) as \(N \mod 8\), which gives the remainder when \(N\) is divided by 8.
Update \(N\) using integer division:
\[ N \gets \lfloor N / 8 \rfloor \]Repeat this process until \(N = 0\).
Collect the octal digits \(d_0, d_1, \ldots, d_k\) in reverse order.
Reverse the order of the collected octal digits to obtain the correct octal representation:
\[ O = d_k d_{k-1} \ldots d_1 d_0 \]Return \(O\).
Example of Decimal to Octal Conversion
Consider the decimal number \(10\). We convert it to octal using the algorithm:
Initial Number (\(N = 10\))
Compute the remainder: \(10 \mod 8 = 2\)
Quotient: \(10 \div 8 = 1\) (integer division)
Store \(2\) in
octal_digits
.
Next Number (\(N = 1\))
Compute the remainder: \(1 \mod 8 = 1\)
Quotient: \(1 \div 8 = 0\)
Store \(1\) in
octal_digits
.
Reversing and Combining the Digits
octal_digits
(in reverse order of computation): \([2, 1]\).Reverse the digits to obtain \([1, 2]\).
Join the digits to form the octal number \(12\).
Final Result: The octal representation of \(10\) is \(12\).
def dec_to_oct(decimal_value):
if decimal_value == 0:
return "0"
octal_string = ""
while decimal_value > 0:
octal_string = str(decimal_value % 8) + octal_string
decimal_value //= 8
return octal_string
decimal_value = 10
octal_string = dec_to_oct(decimal_value)
print("Octal value:", octal_string)
Octal value: 12
If we change the input value to \(87\), the output will be:
decimal_value = 87
octal_string = dec_to_oct(decimal_value)
print("Octal value:", octal_string)
Octal value: 127
Octal to Decimal#
The conversion of an octal number to decimal involves summing up each octal digit multiplied by \(8^n\), where \(n\) represents the position of the digit from the rightmost bit (starting at \(0\)). This method allows for a straightforward computation of the decimal equivalent of an octal number. For example, the octal number \(12\) is converted to decimal by calculating \(1 \times 8^1 + 2 \times 8^0 = 10\).
Algorithm 6 (Octal to Decimal Conversion)
Input: An octal string \(O\)
Output: Decimal representation of \(O\)
Represent the octal string \(O\) as \(d_k d_{k-1} \ldots d_1 d_0\), where \(d_i \in \{0, 1, \dots, 7\}\) and \(k\) is the index of the most significant digit (MSD).
Compute the decimal equivalent \(N\) using the positional value of each octal digit:
\[ N = \sum_{i=0}^k d_i \cdot 8^i \]Here, \(d_i\) is the octal digit at position \(i\), and \(8^i\) represents its positional weight.
Evaluate the sum by iterating through each digit \(d_i\) in \(O\) from right to left:
Multiply each \(d_i\) by \(8^i\) and add the result to the running total \(N\).
Return \(N\).
Example of Octal to Decimal Conversion
Consider the octal number \(12\). We convert it to decimal using the algorithm:
Octal Number: \(12\) (read from left to right)
Most Significant Digit (\(1\)):
\(1 \times 8^1 = 8\)Least Significant Digit (\(2\)):
\(2 \times 8^0 = 2\)
Summing the Results:
\(8 + 2 = 10\)
Final Result: The decimal representation of \(12\) is \(10\).
def oct_to_dec(octal_string):
if not is_octal(octal_string):
return 0
decimal_value = 0
for i, character in enumerate(reversed(octal_string)):
decimal_value += int(character) * (8 ** i)
return decimal_value
octal_string = "12"
decimal_value = oct_to_dec(octal_string)
print("Decimal value:", decimal_value)
Decimal value: 10
If we change the input value to \(26\), the output will be:
octal_string = "26"
decimal_value = oct_to_dec(octal_string)
print("Decimal value:", decimal_value)
Decimal value: 22
Octal to Binary#
The conversion of an octal number to binary involves translating each octal digit into its 3-bit binary equivalent. This method ensures an accurate and efficient conversion because each octal digit corresponds directly to three binary digits. For example, the octal number \(12\) is converted to binary by mapping \(1\) to \(001\) and \(2\) to \(010\), resulting in \(001010\).
Algorithm 7 (Octal to Binary Conversion)
Input: An octal string \(O\)
Output: Binary representation of \(O\)
Represent each octal digit \(d\) as a 3-bit binary string using a mapping:
\[ d \in \{0, 1, \dots, 7\} \quad \to \quad \text{3-bit binary equivalent.} \]Example mapping:
\[ \{'0': '000', '1': '001', \dots, '7': '111'\}. \]Let the binary result \(B\) be an empty string.
For each octal digit \(d\) in \(O\):
\[ B \gets B \, || \, \text{binary equivalent of } d \]Here, \(||\) denotes concatenation of strings.
The resulting binary string \(B\) represents the equivalent binary value of the octal string \(O\).
Return \(B\).
Explanation
Consider the octal number \(12\). We convert it to binary using the algorithm:
Octal number: \(12\)
Digit \(1\):
Using the mapping \(1 \to 001\), store \(001\).Digit \(2\):
Using the mapping \(2 \to 010\), store \(010\).
Combine the binary equivalents:
Concatenate \(001\) and \(010\) to form \(001010\).
Result: The binary representation of \(12\) is \(001010\).
def oct_to_bin(octal_string):
if not is_octal(octal_string):
return ""
binary_string = ""
for octal_character in octal_string:
octal_value = int(octal_character)
for i in range(2, -1, -1):
binary_string += "1" if (octal_value >> i) & 1 else "0"
first_one = binary_string.find('1')
return "0" if first_one == -1 else binary_string[first_one:]
octal_string = "12"
binary_string = oct_to_bin(octal_string)
print("Binary value:", binary_string)
Binary value: 1010
If we change the input value to \(26\), the output will be:
octal_string = "26"
binary_string = oct_to_bin(octal_string)
print("Binary value:", binary_string)
Binary value: 10110
Binary to Octal#
The conversion of a binary number to octal involves grouping the binary digits into sets of three bits, starting from the rightmost bit. Each group of three bits corresponds directly to an octal digit, making the conversion straightforward. For example, the binary number \(101010\) is grouped as \(101\) and \(010\), which map to the octal digits \(5\) and \(2\), resulting in \(52\).
Algorithm 8 (Binary to Octal Conversion)
Input: A binary string \(B\)
Output: Octal representation of \(B\)
Group the binary digits in \(B\) into blocks of 3 bits starting from the right.
If the length of \(B\) is not a multiple of 3, pad it with leading zeros:
\[ B \gets \text{'0'}^{m} || B, \quad m = 3 - (\text{length of } B \mod 3). \]
Let the octal result \(O\) be an empty string.
For each 3-bit group \(b_i\):
Convert \(b_i\) to its octal equivalent using a mapping:
\[ b_i \in \{000, 001, \dots, 111\} \quad \to \quad \text{octal digit.} \]Example mapping:
\[ \{'000': '0', '001': '1', \dots, '111': '7'\}. \]Append the octal equivalent of \(b_i\) to \(O\):
\[ O \gets O \, || \, \text{octal equivalent of } b_i \]
The resulting octal string \(O\) represents the equivalent octal value of the binary string \(B\).
Return \(O\).
Example of Binary to Octal Conversion
Consider the binary number \(101010\). We convert it to octal using the algorithm:
Binary Number: \(101010\)
Ensure the length is a multiple of 3:
The length is already 6, so no padding is needed.Group the binary digits into sets of three:
\(101\), \(010\).
Map Each Group to its Octal Equivalent:
\(101 \to 5\)
\(010 \to 2\)
Combine the Octal Digits:
Concatenate \(5\) and \(2\) to form \(52\).
Final Result: The octal representation of \(101010\) is \(52\).
def bin_to_oct(binary_string):
if not is_binary(binary_string):
return ""
padding = (3 - (len(binary_string) % 3)) % 3
padded_binary_string = "0" * padding + binary_string
octal_string = ""
for i in range(0, len(padded_binary_string), 3):
octal_value = int(padded_binary_string[i:i+3], 2)
octal_string += str(octal_value)
first_non_zero = octal_string.find('1')
return "0" if first_non_zero == -1 else octal_string[first_non_zero:]
binary_string = "101010"
octal_string = bin_to_oct(binary_string)
print("Octal value:", octal_string)
Octal value: 0
If we change the input value to \(101110010\), the output will be:
binary_string = "101110010"
octal_string = bin_to_oct(binary_string)
print("Octal value:", octal_string)
Octal value: 0
Hexadecimal to Octal#
Converting a hexadecimal number to octal involves a two-step process. First, the hexadecimal number is converted to its binary equivalent. Then, the binary number is converted to its octal equivalent by grouping the binary digits into sets of three, starting from the rightmost bit. This process ensures an accurate translation from hexadecimal to octal.
Algorithm 9 (Hexadecimal to Octal Conversion)
Input: A hexadecimal string \(H\)
Output: Octal representation of \(H\)
Step 1: Convert Hexadecimal to Binary
Represent each hexadecimal digit \(h\) as its 4-bit binary equivalent.
Concatenate the binary equivalents to form a binary string \(B\).
Step 2: Convert Binary to Octal
Pad \(B\) with leading zeros, if necessary, to make its length a multiple of 3.
Split \(B\) into groups of 3 bits.
Map each 3-bit group to its octal equivalent and concatenate the results to form the octal string \(O\).
Return \(O\).
Example of Hexadecimal to Octal Conversion
Consider the hexadecimal number \(A3\). We convert it to octal using the algorithm:
Step 1: Convert to Binary
Hexadecimal \(A\): \(A \to 1010\)
Hexadecimal \(3\): \(3 \to 0011\)
Combined binary: \(10100011\)
Step 2: Convert Binary to Octal
The binary number \(10100011\) is already a multiple of 3 (no padding needed).
Group the binary digits into sets of three: \(101\), \(000\), \(011\).
Map each group:
\(101 \to 5\)
\(000 \to 0\)
\(011 \to 3\)
Combine the Octal Digits
Concatenate \(5\), \(0\), and \(3\) to form \(503\).
Final Result: The octal representation of \(A3\) is \(503\).
IMPORTANT
This function relies on the hex_to_bin
and the bin_to_oct
functions defined above.
def hex_to_oct(hex_string):
if not is_hex(hex_string):
return ""
binary_string = hex_to_bin(hex_string)
return bin_to_oct(binary_string)
hex_string = "A3"
octal_string = hex_to_oct(hex_string)
print("Octal value:", octal_string)
Octal value: 0
If we change the input value to \(FAA\), the output will be:
hex_string = "FAA"
octal_string = hex_to_oct(hex_string)
print("Octal value:", octal_string)
Octal value: 0
Octal to Hexadecimal#
Converting an octal number to hexadecimal involves a two-step process. First, the octal number is converted to its binary equivalent by mapping each octal digit to its 3-bit binary representation. Then, the binary number is grouped into sets of four bits (starting from the rightmost bit) to map each group to its hexadecimal equivalent. This method ensures an efficient conversion from octal to hexadecimal.
Algorithm 10 (Octal to Hexadecimal Conversion)
Input: An octal string \(O\)
Output: Hexadecimal representation of \(O\)
Step 1: Convert Octal to Binary
Represent each octal digit \(d\) as its 3-bit binary equivalent.
Concatenate the binary equivalents to form a binary string \(B\).
Step 2: Convert Binary to Hexadecimal
Pad \(B\) with leading zeros, if necessary, to make its length a multiple of 4.
Split \(B\) into groups of 4 bits.
Map each 4-bit group to its hexadecimal equivalent and concatenate the results to form the hexadecimal string \(H\).
Return \(H\).
Example of Octal to Hexadecimal Conversion
Consider the octal number \(503\). We convert it to hexadecimal using the algorithm:
Step 1: Convert to Binary
Octal \(5\): \(5 \to 101\)
Octal \(0\): \(0 \to 000\)
Octal \(3\): \(3 \to 011\)
Combined binary: \(101000011\)
Step 2: Convert Binary to Hexadecimal
Pad the binary number to a multiple of 4:
\(101000011\) becomes \(000101000011\).Group the binary digits into sets of four: \(0001\), \(0100\), \(0011\).
Map each group:
\(0001 \to 1\)
\(0100 \to 4\)
\(0011 \to 3\)
Combine the Hexadecimal Digits
Concatenate \(1\), \(4\), and \(3\) to form \(143\).
Final Result: The hexadecimal representation of \(503\) is \(143\).
IMPORTANT
This function relies on the oct_to_bin
and the bin_to_hex
functions defined above.
def oct_to_hex(octal_string):
if not is_octal(octal_string):
return ""
binary_string = oct_to_bin(octal_string)
return bin_to_hex(binary_string)
octal_string = "12"
hex_string = oct_to_hex(octal_string)
print("Hexadecimal value:", hex_string)
Hexadecimal value: A
If we change the input value to \(26\), the output will be:
octal_string = "26"
hex_string = oct_to_hex(octal_string)
print("Hexadecimal value:", hex_string)
Hexadecimal value: 16