Decimal to binary (and vice-versa)(十进制到二进制(反之亦然))
问题描述
谁能给出一个c++代码的例子,可以很容易地将十进制值转换为二进制,并将二进制值转换为十进制?
Can anybody give an example of c++ code that can easily convert a decimal value to binary and a binary value to decimal please?
推荐答案
嗯,你的问题真的很模糊,所以这个答案是一样的.
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
这是一种转换为二进制的方法,它使用更类似编程"的方法而不是类似数学"的方法,因为缺乏更好的描述(尽管两者实际上是相同的,因为这个只是替换了除法右移,按位取模,循环递归.这是另一种思考方式,因为这表明您正在提取单个位).
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:
- 十进制转二进制
- 二进制转十进制
这篇关于十进制到二进制(反之亦然)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:十进制到二进制(反之亦然)
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
