[英]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.我们在课堂上得到了这个问题,去写一个将十进制数转换为二进制数的算法,明天提出来,我自己也试过这个问题。
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;
}
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.