๐
Date: Jan 24, 2026
๐ฅ Topic: Number System Conversions (Algorithms)
๐ Decimal to Binary (The Code Logic)
While the Power Rule is good for humans, computers use the Division Method to convert large numbers.
- Divide the number by 2.
- Store the Remainder (0 or 1).
- Repeat until the number becomes 0.
- Reverse the stored remainders to get the Binary.
๐ป Day 24 Code: Decimal to Binary Converter
I wrote a C++ program that takes a decimal number and converts it to binary using an array to store bits.
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter a Decimal Number: ";
cin >> n;
int binaryNum[32]; // Array to store binary bits
int i = 0;
// Conversion Algorithm
while (n > 0) {
binaryNum[i] = n % 2; // Store remainder
n = n / 2; // Divide number
i++;
}
// Printing in Reverse
cout << "Binary: ";
for (int j = i - 1; j >= 0; j--) {
cout << binaryNum[j];
}
cout << endl;
return 0;
}
๐ Binary to Decimal
To go back (e.g., 101 -> 5), we multiply each digit by its Power of 2 (1, 2, 4, 8...).
(1 * 4) + (0 * 2) + (1 * 1) = 5
⏭️ Next Up: Strings
Numbers are cool, but software is built on Text.
Starting tomorrow, I will learn how C++ handles text using Strings & Character Arrays.
No comments:
Post a Comment