二进制到十进制
Binary to decimal
int rem, count = 0;
long int n=0, b, i;
count << "Enter the Binary value to convert in Decimal = ";
cin >> b;
i = b;
while (b > 0)
{
rem = b % 10;
n = n + rem * pow(2, count);
count++;
b = b / 10;
}
cout << "The decimal value of Binary no. = " << i << " = " << n;
getch();
我用C++制作了这个简单的程序,现在我想用 C# 实现它,但我无法这样做,因为我不知道如何实现我在循环中使用的逻辑。因为在C++中关键字 pow
用于乘以2
的值,所以我不知道如何在 C# 中做到这一点。
不,pow()
不是关键字,它是标准库math.h
中的函数。
在这种情况下,对于 C++ 和 C#,您可以轻松地通过位移替换它:
(int) pow(2, count) == 1 << count
以上对于count
的所有正值都是正确的,直到平台/语言的精度极限。
我相信使用移位从整体上解决问题要容易得多。
检查这个:
int bintodec(int decimal);
int _tmain(int argc, _TCHAR* argv[])
{
int decimal;
printf("Enter an integer (0's and 1's): ");
scanf_s("%d", &decimal);
printf("The decimal equivalent is %d.n", bintodec(decimal));
getchar();
getchar();
return 0;
}
int bintodec(int decimal)
{
int total = 0;
int power = 1;
while(decimal > 0)
{
total += decimal % 10 * power;
decimal = decimal / 10;
power = power * 2;
}
return total;
}
你必须
处理C#
中的数据类型
long int n=0, b, i; // long int is not valid type in C#, Use only int type.
将pow()
替换为Math.Pow()
pow(2, count); // pow() is a function in C/C++
((int)Math.Pow(2, count)) // Math.Pow() is equivalent of pow in C#.
// Math.Pow() returns a double value, so cast it to int
看看 Math.Pow 方法。
通常,数学类提供了您正在寻找的许多功能。
互联网上其他地方的完整代码示例是在此处输入链接描述。
public int BinaryToDecimal(string data)
{
int result = 0;
char[] numbers = data.ToCharArray();
try
{
if (!IsNumeric(data))
error = "Invalid Value - This is not a numeric value";
else
{
for (int counter = numbers.Length; counter > 0; counter--)
{
if ((numbers[counter - 1].ToString() != "0") && (numbers[counter - 1].ToString() != "1"))
error = "Invalid Value - This is not a binary number";
else
{
int num = int.Parse(numbers[counter - 1].ToString());
int exp = numbers.Length - counter;
result += (Convert.ToInt16(Math.Pow(2, exp)) * num);
}
}
}
}
catch (Exception ex)
{
error = ex.Message;
}
return result;
}
http://zamirsblog.blogspot.com/2011/10/convert-binary-to-decimal-in-c.html
相关文章:
- visual在c++中将十进制数转换为二进制数
- C++十进制到二进制,如何转换
- C++从二进制转换为十进制数
- 我编写了代码将十进制分数转换为其二进制等效数.它编译得很好,但在执行时挂起
- uint8_t同一二进制文件的不同十进制值
- 十进制到二进制转换器 c++
- 如何在C ++中将二进制字符串128位转换为十进制字符串?
- 将二进制转换为十进制,我如何要求用户仅输入二进制
- C++:二进制到十进制w/转换过程的外观
- 如何在C++中将二进制编码十进制转换为 int
- 如何使用链表将负十进制数转换为二进制?
- 十进制,包括负到 32 位二进制转换器
- 输入 1024 后十进制到二进制转换的输出错误?
- 以正确的顺序从十进制转换为二进制
- 二进制反转为十进制数
- 十进制到二进制的实现不能完全适用于我大学的检查器。问题或提示可能是什么
- 如何将值从十进制存储为二进制,使其在 C++ 中将值保存在 6 位
- 使用指数将十进制转换为二进制
- 将40个字节长的数据框从十六进制转换为二进制,然后转换为十进制
- 我通过迭代加法将二进制数转换为十进制并检查单个字符(请参阅代码)的方法有什么问题?