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:
- 十进制转二进制
- 二进制转十进制
这篇关于十进制到二进制(反之亦然)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:十进制到二进制(反之亦然)
基础教程推荐
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04