简体   繁体   English

如何使用算法将十进制数转换为二进制数

[英]how do I convert a decimal number to binary number using an algorithm

We were given this question in class to go and write an algorithm for converting a decimal number to binary number and tomorrow present it, I myself had tried the question.我们在课堂上得到了这个问题,去写一个将十进制数转换为二进制数的算法,明天提出来,我自己也试过这个问题。

  1. start开始
  2. i=0, count=0我=0,计数=0
  3. if i<=n goto step 4如果 i<=n 转到第 4 步
  4. r=n%2 r=n%2
  5. n=n/2 n=n/2
  6. count= count+1计数=计数+1
  7. store remainder存储余数
  8. if count=9 true print number if count=9 true 打印数量
  9. else goto step 3否则转到第 3 步
  10. end结尾

If you want a more STL-ish and C++-ish solution, I suggest you using std::bitset (introduced in C++11) which represents a fixed-size sequence of N bits.如果你想要一个更多的 STL-ish 和 C++-ish 解决方案,我建议你使用std::bitset (在 C++11 中引入),它代表一个固定大小的 N 位序列。

#include <bitset>
#include <string>
#include <climits>
#include <iostream>

std::string int_to_binary(int const value) {
    std::bitset<sizeof(int) * CHAR_BIT> bs(value);
    return bs.to_string();
}

int main() {
    std::cout << int_to_binary(1) << std::endl;
    std::cout << int_to_binary(2) << std::endl;
    std::cout << int_to_binary(3) << std::endl;

    return 0;
}

Check it out live . 现场查看。

Furthermore, if you want to make your int_to_binary function a bit more generic, you could turn it into a template function and take some time and research about SFINAE and std::enable_if .此外,如果你想让你的int_to_binary函数更通用一点,你可以把它变成一个模板函数,花一些时间研究 SFINAE 和std::enable_if Here is how your function now could look like:以下是您的函数现在的样子:

template <typename T,
          typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
std::string int_to_binary(T const value) {
    std::bitset<sizeof(T) * CHAR_BIT> bs(value);
    return bs.to_string();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM