如何在不使用任何库的情况下将十进制转换为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这样的库。你能告诉我没有库怎么做吗?

你可以试试这个方法。

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 << ' ';
}
}

相关内容