Conversion Operations
Learn how to perform basic mathematical conversion operations for different values such as binary to decimal, or hex to octal.
Written by: Brianna Laird
Last updated: December 2024
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.
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.
#include <iostream>#include <string>using namespace std;
bool is_binary(const string &binary_string){ for (char character : binary_string) { if (character != '0' && character != '1') return false; } return !binary_string.empty();}
bool IsBinary(string binaryString){ foreach (char character in binaryString) { if (character != '0' && character != '1') return false; } return !string.IsNullOrEmpty(binaryString);}
def is_binary(binary_string): return all(character in '01' for character in binary_string) and bool(binary_string)
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.
bool is_hex(const string &hex_string){ for (char character : hex_string) { if (!((character >= '0' && character <= '9') || (character >= 'A' && character <= 'F') || (character >= 'a' && character <= 'f'))) return false; } return !hex_string.empty();}
bool IsHex(string hexString){ foreach (char character in hexString) { if (!((character >= '0' && character <= '9') || (character >= 'A' && character <= 'F') || (character >= 'a' && character <= 'f'))) return false; } return !string.IsNullOrEmpty(hexString);}
def is_hex(hex_string): return all(character in '0123456789ABCDEFabcdef' for character in hex_string) and bool(hex_string)
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.
bool is_octal(const string &octal_string){ for (char character : octal_string) { if (character < '0' || character > '7') return false; } return !octal_string.empty();}
bool IsOctal(string octalString){ foreach (char character in octalString) { if (character < '0' || character > '7') return false; } return !string.IsNullOrEmpty(octalString);}
def is_octal(octal_string): return all(character in '01234567' for character in octal_string) and bool(octal_string)
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
Converting a decimal number to binary involves dividing the number by 2 repeatedly and recording the remainder for each division. These remainders, read in reverse order, form the binary representation of the decimal number. For example, to convert the decimal number 10 to binary, you would perform the following steps:
string dec_to_bin(unsigned int decimal_value){ if (decimal_value == 0) return "0";
string binary_string; while (decimal_value > 0) { binary_string = ((decimal_value & 1) ? "1" : "0") + binary_string; decimal_value >>= 1; } return binary_string;
string DecToBin(uint decimalValue){ if (decimalValue == 0) return "0";
string binaryString = ""; while (decimalValue > 0) { binaryString = ((decimalValue & 1) == 1 ? "1" : "0") + binaryString; decimalValue >>= 1; } return binaryString;}
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
Using this function
To use this function in your code, you can call it with a decimal value as an argument. For example, to convert the decimal number 10 to binary, you would call the function as follows:
unsigned int decimal_value = 10;string binary_string = dec_to_bin(decimal_value);cout << "Binary value: " << binary_string << endl;
uint decimalValue = 10;string binaryString = DecToBin(decimalValue);Console.WriteLine("Binary value: " + binaryString);
decimal_value = 10binary_string = dec_to_bin(decimal_value)print("Binary value:", binary_string)
Expected Output
The output of the above code will be:
Binary value: 1010
If we change the input value to
Binary value: 10110
Binary to Decimal
Converting a binary number to decimal involves multiplying each digit by
unsigned int bin_to_dec(const string &binary_string){ if (!is_binary(binary_string)) { return 0; }
unsigned int decimal_value = 0; for (size_t i = 0; i < binary_string.size(); i++) { if (binary_string[i] == '1') { decimal_value += (1 << (binary_string.size() - i - 1)); } } return decimal_value;}
uint BinToDec(string binaryString){ if (!IsBinary(binaryString)) return 0;
uint decimalValue = 0; for (int i = 0; i < binaryString.Length; i++) { if (binaryString[i] == '1') { decimalValue += (uint)(1 << (binaryString.Length - i - 1)); } } return decimalValue;}
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
Using this function
To use this function in your code, you can call it with a binary value as an argument. For example, to convert the binary number
string binary_string = "1010";unsigned int decimal_value = bin_to_dec(binary_string);cout << "Decimal value: " << decimal_value << endl;
string binaryString = "1010";uint decimalValue = BinToDec(binaryString);Console.WriteLine("Decimal value: " + decimalValue);
binary_string = "1010"decimal_value = bin_to_dec(binary_string)print("Decimal value:", decimal_value)
Expected Output
The output of the above code will be:
Decimal value: 10
If we change the input value to
Decimal value: 22
Hexadecimal to Binary
Converting a hexadecimal number to binary involves converting each hexadecimal digit to its binary equivalent. For example, the hexadecimal number
string hex_to_bin(const string &hex_string){ if (!is_hex(hex_string)) { return ""; }
string binary_string; for (char hex_character : hex_string) { int hex_value = 0;
if (hex_character >= '0' && hex_character <= '9') hex_value = hex_character - '0'; else if (hex_character >= 'A' && hex_character <= 'F') hex_value = hex_character - 'A' + 10; else if (hex_character >= 'a' && hex_character <= 'f') hex_value = hex_character - 'a' + 10;
for (int i = 3; i >= 0; i--) { binary_string += ((hex_value >> i) & 1) ? '1' : '0'; } }
if (hex_string.length() == 1) { size_t first_one = binary_string.find_first_not_of('0'); return (first_one == string::npos) ? "0" : binary_string.substr(first_one); }
return binary_string;}
string HexToBin(string hexString){ if (!IsHex(hexString)) return "";
string binaryString = ""; foreach (char hexChar in hexString) { int hexValue = (hexChar >= '0' && hexChar <= '9') ? hexChar - '0' : (hexChar >= 'A' && hexChar <= 'F') ? hexChar - 'A' + 10 : hexChar - 'a' + 10;
for (int i = 3; i >= 0; i--) { binaryString += ((hexValue >> i) & 1) == 1 ? "1" : "0"; } } return binaryString.TrimStart('0');}
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
Using this function
To use this function in your code, you can call it with a hexadecimal value as an argument. For example, to convert the hexadecimal number
string hex_string = "A3";string binary_string = hex_to_bin(hex_string);cout << "Binary value: " << binary_string << endl;
string hexString = "A3";string binaryString = HexToBin(hexString);Console.WriteLine("Binary value: " + binaryString);
hex_string = "A3"binary_string = hex_to_bin(hex_string)print("Binary value:", binary_string)
Expected Output
The output of the above code will be:
Binary value: 10100011
If we change the input value to
Binary value: 1111
Binary to Hexadecimal
Converting a binary number to hexadecimal involves grouping the binary digits into sets of four, starting from the rightmost bit. Each group of four bits corresponds to a single hexadecimal digit, allowing you to convert the binary number to its hexadecimal equivalent. For example, the binary number
string bin_to_hex(const string &binary_string){ if (!is_binary(binary_string)) { return ""; }
string hex_string; int length = binary_string.length();
int padding = (4 - (length % 4)) % 4; string padded_binary_string = string(padding, '0') + binary_string;
for (size_t i = 0; i < padded_binary_string.length(); i += 4) { int hex_value = 0; for (size_t j = 0; j < 4; j++) { hex_value <<= 1; if (padded_binary_string[i + j] == '1') hex_value |= 1; }
if (hex_value < 10) hex_string += '0' + hex_value; else hex_string += 'A' + (hex_value - 10); } return hex_string;}
string BinToHex(string binaryString){ if (!IsBinary(binaryString)) return "";
string paddedBinaryString = binaryString.PadLeft((binaryString.Length + 3) / 4 * 4, '0'); string hexString = "";
for (int i = 0; i < paddedBinaryString.Length; i += 4) { int hexValue = 0; for (int j = 0; j < 4; j++) { hexValue <<= 1; if (paddedBinaryString[i + j] == '1') hexValue |= 1; }
if (hexValue < 10) hexString += (char)('0' + hexValue); else hexString += (char)('A' + (hexValue - 10)); } return hexString;}
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
Using this function
To use this function in your code, you can call it with a binary value as an argument. For example, to convert the binary number
string binary_string = "10100011";string hex_string = bin_to_hex(binary_string);cout << "Hexadecimal value: " << hex_string << endl;
string binaryString = "10100011";string hexString = BinToHex(binaryString);Console.WriteLine("Hexadecimal value: " + hexString);
binary_string = "10100011"hex_string = bin_to_hex(binary_string)print("Hexadecimal value:", hex_string)
Expected Output
The output of the above code will be:
Hexadecimal value: A3
If we change the input value to
Hexadecimal value: F
Decimal to Octal
Converting a decimal number to octal involves dividing the number by 8 repeatedly and recording the remainder for each division. These remainders, read in reverse order, form the octal representation of the decimal number. For example, to convert the decimal number 10 to octal, you would perform the following steps:
string dec_to_oct(unsigned int decimal_value){ if (decimal_value == 0) return "0";
string octal_string; while (decimal_value > 0) { octal_string = to_string(decimal_value % 8) + octal_string; decimal_value /= 8; } return octal_string;}
string DecToOct(uint decimalValue){ if (decimalValue == 0) return "0";
string octalString = ""; while (decimalValue > 0) { octalString = (decimalValue % 8).ToString() + octalString; decimalValue /= 8; } return octalString;}
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
Using this function
To use this function in your code, you can call it with a decimal value as an argument. For example, to convert the decimal number 10 to octal, you would call the function as follows:
unsigned int decimal_value = 10;string octal_string = dec_to_oct(decimal_value);cout << "Octal value: " << octal_string << endl;
uint decimalValue = 10;string octalString = DecToOct(decimalValue);Console.WriteLine("Octal value: " + octalString);
decimal_value = 10octal_string = dec_to_oct(decimal_value)print("Octal value:", octal_string)
Expected Output
The output of the above code will be:
Octal value: 12
If we change the input value to
Octal value: 26
Octal to Decimal
Converting an octal number to decimal involves multiplying each digit by
unsigned int oct_to_dec(const string &octal_string){ if (!is_octal(octal_string)) { return 0; }
unsigned int decimal_value = 0; for (size_t i = 0; i < octal_string.size(); i++) { decimal_value = decimal_value * 8 + (octal_string[i] - '0'); } return decimal_value;}
uint OctToDec(string octalString){ if (!IsOctal(octalString)) return 0;
uint decimalValue = 0; foreach (char octChar in octalString) { decimalValue = decimalValue * 8 + (uint)(octChar - '0'); } return decimalValue;}
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
Using this function
To use this function in your code, you can call it with an octal value as an argument. For example, to convert the octal number 12 to decimal, you would call the function as follows:
string octal_string = "12";unsigned int decimal_value = oct_to_dec(octal_string);cout << "Decimal value: " << decimal_value << endl;
string octalString = "12";uint decimalValue = OctToDec(octalString);Console.WriteLine("Decimal value: " + decimalValue);
octal_string = "12"decimal_value = oct_to_dec(octal_string)print("Decimal value:", decimal_value)
Expected Output
The output of the above code will be:
Decimal value: 10
If we change the input value to
Decimal value: 22
Octal to Binary
Converting an octal number to binary involves converting each octal digit to its binary equivalent. For example, the octal number
string oct_to_bin(const string &octal_string){ if (!is_octal(octal_string)) { return ""; }
string binary_string; for (char octal_character : octal_string) { int octal_value = octal_character - '0';
for (int i = 2; i >= 0; i--) { binary_string += ((octal_value >> i) & 1) ? '1' : '0'; } }
size_t first_one = binary_string.find_first_not_of('0'); return (first_one == string::npos) ? "0" : binary_string.substr(first_one);}
string OctToBin(string octalString){ if (!IsOctal(octalString)) return "";
string binaryString = ""; foreach (char octChar in octalString) { int octValue = octChar - '0'; for (int i = 2; i >= 0; i--) { binaryString += ((octValue >> i) & 1) == 1 ? "1" : "0"; } } return binaryString.TrimStart('0');}
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:]
Using this function
To use this function in your code, you can call it with an octal value as an argument. For example, to convert the octal number 12 to binary, you would call the function as follows:
string octal_string = "12";string binary_string = oct_to_bin(octal_string);cout << "Binary value: " << binary_string << endl;
string octalString = "12";string binaryString = OctToBin(octalString);Console.WriteLine("Binary value: " + binaryString);
octal_string = "12"binary_string = oct_to_bin(octal_string)print("Binary value:", binary_string)
Expected Output
The output of the above code will be:
Binary value: 1010
If we change the input value to
Binary value: 10110
Binary to Octal
Converting a binary number to octal involves grouping the binary digits into sets of three, starting from the rightmost bit. Each group of three bits corresponds to a single octal digit, allowing you to convert the binary number to its octal equivalent. For example, the binary number
string bin_to_oct(const string &binary_string){ if (!is_binary(binary_string)) { return ""; }
string octal_string;
int padding = (3 - (binary_string.length() % 3)) % 3; string padded_binary_string = string(padding, '0') + binary_string;
for (size_t i = 0; i < padded_binary_string.length(); i += 3) { int octal_value = 0; for (size_t j = 0; j < 3; j++) { octal_value <<= 1; if (padded_binary_string[i + j] == '1') octal_value |= 1; }
octal_string += '0' + octal_value; }
size_t first_non_zero = octal_string.find_first_not_of('0'); return (first_non_zero == string::npos) ? "0" : octal_string.substr(first_non_zero);}
string BinToOct(string binaryString){ if (!IsBinary(binaryString)) return "";
string paddedBinaryString = binaryString.PadLeft((binaryString.Length + 2) / 3 * 3, '0'); string octalString = "";
for (int i = 0; i < paddedBinaryString.Length; i += 3) { int octValue = 0; for (int j = 0; j < 3; j++) { octValue <<= 1; if (paddedBinaryString[i + j] == '1') octValue |= 1; } octalString += (char)('0' + octValue); } return octalString.TrimStart('0');}
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:]
Using this function
To use this function in your code, you can call it with a binary value as an argument. For example, to convert the binary number
string binary_string = "101010";string octal_string = bin_to_oct(binary_string);cout << "Octal value: " << octal_string << endl;
string binaryString = "101010";string octalString = BinToOct(binaryString);Console.WriteLine("Octal value: " + octalString);
binary_string = "101010"octal_string = bin_to_oct(binary_string)print("Octal value:", octal_string)
Expected Output
The output of the above code will be:
Octal value: 52
If we change the input value to
Octal value: 26
Hexadecimal to Octal
Converting a hexadecimal number to octal involves converting the hexadecimal number to binary and then converting the binary number to octal. This process can be implemented programmatically to convert any hexadecimal number to its octal equivalent.
string hex_to_oct(const string &hex_string){ if (!is_hex(hex_string)) { return ""; }
string binary_string = hex_to_bin(hex_string); return bin_to_oct(binary_string);}
string HexToOct(string hexString) => BinToOct(HexToBin(hexString));
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)
Using this function
To use this function in your code, you can call it with a hexadecimal value as an argument. For example, to convert the hexadecimal number
string hex_string = "A3";string octal_string = hex_to_oct(hex_string);cout << "Octal value: " << octal_string << endl;
string hexString = "A3";string octalString = HexToOct(hexString);Console.WriteLine("Octal value: " + octalString);
hex_string = "A3"octal_string = hex_to_oct(hex_string)print("Octal value:", octal_string)
Expected Output
The output of the above code will be:
Octal value: 123
If we change the input value to
Octal value: 17
Octal to Hexadecimal
Converting an octal number to hexadecimal involves converting the octal number to binary and then converting the binary number to hexadecimal. This process can be implemented programmatically to convert any octal number to its hexadecimal equivalent.
string oct_to_hex(const string &octal_string){ if (!is_octal(octal_string)) { return ""; }
string binary_string = oct_to_bin(octal_string); return bin_to_hex(binary_string);}
string OctToHex(string octalString) => BinToHex(OctToBin(octalString));
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)
Using this function
To use this function in your code, you can call it with an octal value as an argument. For example, to convert the octal number 12 to hexadecimal, you would call the function as follows:
string octal_string = "12";string hex_string = oct_to_hex(octal_string);cout << "Hexadecimal value: " << hex_string << endl;
string octalString = "12";string hexString = OctToHex(octalString);Console.WriteLine("Hexadecimal value: " + hexString);
octal_string = "12"hex_string = oct_to_hex(octal_string)print("Hexadecimal value:", hex_string)
Expected Output
The output of the above code will be:
Hexadecimal value: A
If we change the input value to
Hexadecimal value: 16
Summary
This guide showed you how to convert numbers between different number systems, including decimal, binary, octal, and hexadecimal. You learned how to implement conversion functions in C++, C#, and Python, and how to use these functions to convert numbers between different number systems. By following the examples and explanations provided in this guide, you should now have a better understanding of how to convert numbers between different number systems programmatically. You can use this knowledge to implement number system conversion functions in your own projects and applications.