A C++ console program that converts numbers between decimal, binary, hexadecimal, and octal.
The program shows a menu with these options:
- Convert decimal to binary
- Convert binary to decimal
- Convert hexadecimal to binary
- Convert binary to hexadecimal
- Convert octal to binary
- Convert binary to octal
- Exit
You type in a number and it prints the converted value. It keeps looping until you choose exit.
decimalToBinary repeatedly divides by 2 and builds the binary result digit by digit, using increasing place values (1, 10, 100, ...) so each bit lands in the right spot of the output integer.
binaryToDecimal reads the binary number one digit at a time from the right, multiplying each digit by the correct power of 2 and adding it to a running total.
hexadecimalToBinary and octalToBinary convert each digit of the input to its fixed-width binary equivalent (4 bits per hex digit, 3 bits per octal digit), then strip any leading zeros from the result.
binaryToHexadecimal and binaryToOctal group the binary string into chunks from the right (4 bits for hex, 3 bits for octal), convert each chunk to its digit, then reverse the result into the correct order.
g++ -o converter code.cpp
./converter
On Windows with MinGW:
g++ -o converter.exe code.cpp
converter.exe
Hex input is capped at 8 digits. Binary and decimal results are stored as plain ints, so this works for numbers small enough that the binary representation still fits in an int when read as base 10 digits.