c++ - 如何在不使用任何库的情况下将十进制转换为 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 << ' ';
}
}
推荐阅读
- php - Wordpress 在 URL 中显示 /index1.php/
- android - 我们怎样才能得到这种类型的 json 数据呢?
- c - 用 C 中的等效 HTML 实体替换字符/符号
- javascript - 为什么日期函数没有返回我预期的输出?
- r - 如何使用带有 mtcars 数据的 factor() 创建一个虚拟对象?
- google-sheets - 如何获取字符串输入的参考号?
- firebase - Firebase 分析网络连接(网址、端口、IP 地址)?
- javascript - 即使没有更多记录,Javascript ajax 也会显示相同的消息
- html - CSS 响应式卡片
- android - 如何在 react-native 中运行简单程序但出现错误