首页 > 解决方案 > 如何在不使用任何库的情况下将十进制转换为 bcd

问题描述

string decimal_to_bcd(int num)
{
   if (num == 0) {
        cout << "0000";
        return 0;
    }

    // To store the reverse of n
    int rev = 0;

    // Reversing the digits
    while (num > 0) {
        rev = rev * 10 + (num % 10);
        num /= 10;
    }
    // Iterate through all digits in rev
    while (rev > 0) {

        // Find Binary for each digit
        // using bit set
        bitset<4> b(rev % 10);

        // Print the Binary conversion
        // for current digit
        
        cout << b << ' ';

        // Divide rev by 10 for next digit
        rev /= 10;
}
}

我写了这个,但问题是我不想使用我用过的任何库,比如 bitset。你能帮我在没有图书馆的情况下怎么做吗

标签: c++

解决方案


你可以试试这个方法。

auto dec_to_bin(int n)
{
    std::vector<std::bitset<4>> repr;
    while(n > 0){
        repr.push_back(std::bitset<4>(n % 10));
        n /= 10;
    }
    std::reverse(repr.begin(), repr.end());
    return repr;
}


int main()
{
    for(auto b : dec_to_bin(215)){
        std::cout << b << ' ';
    }
}


推荐阅读