दशमलव से बाइनरी
किसी धनात्मक दशमलव पूर्णांक को बाइनरी में बदलें।
दशमलव से बाइनरी क्या है?
बार-बार दो से भाग देने पर बाइनरी अंक सबसे कम महत्व वाले से सबसे ज़्यादा तक मिलते हैं।
महत्वपूर्ण बातें
- Compiler warnings चालू करके सभी ठीक करें।
- हर value का type और lifetime समझें।
- Input और array bounds validate करें।
C और C++ code examples
main.c
#include <stdio.h>
int main(void) {
unsigned number = 13, value = number; int bits[32], count = 0;
// Store remainders generated from right to left.
do { bits[count++] = value % 2; value /= 2; } while (value);
printf("%u = ", number); while (count) printf("%d", bits[--count]); puts("");
}
13 = 1101
C++
main.cpp
#include <bitset>
#include <iostream>
#include <string>
int main() {
unsigned number = 13;
// Remove leading zeroes from a fixed-width bitset string.
std::string bits = std::bitset<32>(number).to_string();
bits.erase(0, bits.find_first_not_of('0'));
std::cout << number << " = " << bits << '\n';
}
13 = 1101
C और C++ की तुलना
शेषफल सहेजें और उन्हें उल्टे क्रम में प्रिंट करें, क्योंकि भाग देने से आख़िरी अंक पहले मिलता है।
C
C छोटे procedural APIs और representation details स्पष्ट करता है।
C++
C++ low-level model रखकर safer library types जोड़ता है।
अभ्यास
दोनों versions चलाकर बदलें और language guarantees की तुलना करें।
- Invalid और boundary inputs जोड़ें।
- -Wall -Wextra -Wpedantic से compile करें।
- Declarations और implementation अलग करें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
सभी चैलेंज