बाइनरी (बेस-2) संख्या को दशमलव (बेस-10) में बदलने के लिए हम प्रत्येक बिट को उसके स्थान मूल्य (2 की घात) से गुणा करके जोड़ते हैं।
एल्गोरिदम
- दाएं से बाएं (LSB से MSB) प्रत्येक बिट प्रोसेस करें।
- बिट × 2^पोजीशन जोड़ें।
- पोजीशन 0 से शुरू होती है।
उदाहरण
using System;
using System.Collections.Generic;
using System.Text;
namespace Demo {
class MyApplication {
static void Main(string[] args) {
int num = 101; // बाइनरी इनपुट
int binVal = num; // मूल मान सुरक्षित रखें
int decVal = 0;
int baseVal = 1; // 2^0
int rem;
while (num > 0) {
rem = num % 10; // अंतिम बिट प्राप्त करें
decVal = decVal + rem * baseVal; // मान जोड़ें
num = num / 10; // अंतिम बिट हटाएं
baseVal = baseVal * 2; // अगली घात: 1, 2, 4, 8...
}
Console.Write("Binary Number: " + binVal);
Console.Write("\nDecimal: " + decVal);
Console.ReadLine();
}
}
}
आउटपुट
Binary Number: 101 Decimal: 5
चरण-दर-चरण (101₂ के लिए)
| इटरेशन | num | rem (num%10) | baseVal (2^pos) | decVal |
|---|---|---|---|---|
| 1 | 101 | 1 | 1 (2⁰) | 1 |
| 2 | 10 | 0 | 2 (2¹) | 1 |
| 3 | 1 | 1 | 4 (2²) | 5 |
| 4 | 0 | - | - | 5 (समाप्त) |
बिल्ट-इन मेथड (सबसे आसान)
string binary = "101"; int decimalValue = Convert.ToInt32(binary, 2); // 5 // या int decimalValue = int.Parse(binary, System.Globalization.NumberStyles.Binary);
बिटवाइज दृष्टिकोण (स्ट्रिंग के बजाय int इनपुट के लिए)
int binary = 0b101; // C# 7+ बाइनरी लिटरल
int decimal = 0;
int pos = 0;
while (binary > 0) {
if ((binary & 1) == 1)
decimal += 1 << pos;
binary >>= 1;
pos++;
}
बड़े बाइनरी स्ट्रिंग्स के लिए
string largeBinary = "10101010101010101010101010101010"; // int/long में फिट नहीं होगा var bigInt = System.Numerics.BigInteger.Parse(largeBinary, System.Globalization.NumberStyles.Binary);
मुख्य बिंदु
- इनपुट के रूप में
intलेने वाला मैन्युअल तरीका केवल छोटी बाइनरी संख्याओं के लिए काम करता है (अधिकतम 10-11 बिट्स जब तक int ओवरफ्लो नहीं होता)। - स्ट्रिंग इनपुट के लिए
Convert.ToInt32(str, 2)उपयोग करें - कोई आकार सीमा नहीं। - C# 7+ में बाइनरी लिटरल:
0b1010= 10।