C++ 十进制到二进制(反之亦然)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2548282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Decimal to binary (and vice-versa)
提问by Jony
Can anybody give an example of c++ code that can easily convert a decimal value to binary and a binary value to decimal please?
任何人都可以举一个可以轻松将十进制值转换为二进制并将二进制值转换为十进制的 C++ 代码示例吗?
回答by IVlad
Well, your question is really vague, so this answer is the same.
嗯,你的问题真的很模糊,所以这个答案是一样的。
string DecToBin(int number)
{
if ( number == 0 ) return "0";
if ( number == 1 ) return "1";
if ( number % 2 == 0 )
return DecToBin(number / 2) + "0";
else
return DecToBin(number / 2) + "1";
}
int BinToDec(string number)
{
int result = 0, pow = 1;
for ( int i = number.length() - 1; i >= 0; --i, pow <<= 1 )
result += (number[i] - '0') * pow;
return result;
}
You should check for overflow and do input validation of course.
您当然应该检查溢出并进行输入验证。
x << 1 == x * 2
x << 1 == x * 2
Here's a way to convert to binary that uses a more "programming-like" approach rather than a "math-like" approach, for lack of a better description (the two are actually identical though, since this one just replaces divisions by right shifts, modulo by a bitwise and, recursion with a loop. It's kind of another way of thinking about it though, since this makes it obvious you are extracting the individual bits).
这是一种转换为二进制的方法,它使用更“类似编程”的方法而不是“类似数学”的方法,因为缺乏更好的描述(尽管这两者实际上是相同的,因为这只是用右移代替了除法,按位取模,然后循环递归。不过,这是另一种思考方式,因为这使您很明显正在提取单个位)。
string DecToBin2(int number)
{
string result = "";
do
{
if ( (number & 1) == 0 )
result += "0";
else
result += "1";
number >>= 1;
} while ( number );
reverse(result.begin(), result.end());
return result;
}
And here is how to do the conversion on paper:
以下是如何在纸上进行转换:
回答by Jerry Coffin
strtol
will convert a binary string like "011101" to an internal value (which will normally be stored in binary as well, but you don't need to worry much about that). A normal conversion (e.g. operator<<
with std:cout
) will give the same value in decimal.
strtol
会将像 "011101" 这样的二进制字符串转换为内部值(通常也会以二进制形式存储,但您不必太担心)。正常转换(例如operator<<
使用std:cout
)将给出相同的十进制值。
回答by NoriMax
//The shortest solution to convert dec to bin in c++
void dec2bin(int a) {
if(a!=0) dec2bin(a/2);
if(a!=0) cout<<a%2;
}
int main() {
int a;
cout<<"Enter the number: "<<endl;
cin>>a;
dec2bin(a);
return 0;
}
}
回答by Jay
I assume you want a string to binary conversion?
我假设你想要一个字符串到二进制转换?
template<typename T> T stringTo( const std::string& s )
{
std::istringstream iss(s);
T x;
iss >> x;
return x;
};
template<typename T> inline std::string toString( const T& x )
{
std::ostringstream o;
o << x;
return o.str();
}
use these like this:
像这样使用这些:
int x = 32;
std:string decimal = toString<int>(x);
int y = stringTo<int>(decimal);