रिकर्सिव मेथड से दशमलव को बाइनरी में बदलना
दशमलव नंबर सेट करें:
int dec = 30;
रिकर्सिव फंक्शन बनाएं:
public int displayBinary(int dec) {
int res;
if (dec != 0) {
res = (dec % 2) + 10 * displayBinary(dec / 2);
Console.Write(res);
return 0;
} else {
return 0;
}
}
व्याख्या:
dec % 2- अंतिम बिट (0 या 1) देता हैdec / 2- अगले रिकर्सिव कॉल के लिए नंबर को आधा करता है10 * displayBinary(...)- पिछले बिट्स को बाएँ शिफ्ट करता है (दशमलव में 10 से गुणा करने पर)
पूर्ण कोड उदाहरण
using System;
public class Program {
public static void Main(string[] args) {
int dec;
Demo d = new Demo();
dec = 30;
Console.Write("Decimal = " + dec);
Console.Write("\nBinary of {0} = ", dec);
d.displayBinary(dec);
Console.ReadLine();
Console.Write("\n");
}
}
public class Demo {
public int displayBinary(int dec) {
int res;
if (dec != 0) {
res = (dec % 2) + 10 * displayBinary(dec / 2);
Console.Write(res);
return 0;
} else {
return 0;
}
}
}
आउटपुट
Decimal = 30 Binary of 30 = 11110
बेहतर विकल्प: प्रोडक्शन कोड के लिए Convert.ToString(dec, 2) का उपयोग करें जो अधिक कुशल और पठनीय है।