如何在 C# 中用分数将二进制转换为十进制?使用 winform,我试图将二进制数转换为十进制数。我用了输入功能

问题描述 投票:0回答:1
if (binarybtn.Checked == true)
{
    int decVal = 0, baseVal = 1, rem;
    binarytxtbox.Text = textBox1.Text;

    int input = Convert.ToInt32(textBox1.Text);

    while (input > 0)
    {
        
        rem = input % 10;
        decVal = decVal + rem * baseVal;
        input = input / 10;
        baseVal = baseVal * 2;
        
    }

    decimaltxtbox.Text = Convert.ToString(decVal);

    ...

我尝试使用输入功能,但它不接受字符串

"."

c# winforms binary decimal windows-forms-designer
1个回答
0
投票

如果我没理解错的话,你有一个带小数部分的二进制数,比如

10.1 (binary)

而你想把它转换成对应的十进制数

2.5 (decimal)

如果这是你的任务,你可以使用

private static decimal BinaryToDecimal(string value, char decimalSeparator = '.') {
  value = value.Trim();

  int sign = value.StartsWith('-') ? -1 : +1;

  value = value.Trim('-');

  int index = value.IndexOf(decimalSeparator);

  string integerPart = index >= 0 ? value.Substring(0, index) : value;

  decimal result = string.IsNullOrEmpty(integerPart)
    ? 0
    : Convert.ToInt64(integerPart, 2);

  string fractionalPart = index >= 0 ? value.Substring(index + 1) : "";

  for (int i = 0; i < fractionalPart.Length; ++i)
    result += (decimal)(fractionalPart[i] - '0') / (1L << (i + 1));

  return sign * result;
}

用法:

decimaltxtbox.Text = BinaryToDecimal(textBox1.Text);

演示:

using System.Linq;

...

string[] tests = {
  "0",
  "-0",
  "100",
  "-100",
  "10.",
  "-10.",
  "1.1",
  "101.101",
  "-101.101",
  ".1011",
  "-.11011",
  "100.00",
  ".", // <- It seems, you treat it as a valid input
};

string report = string.Join(Environment.NewLine, tests
  .Select(test => $"{test,10} => {BinaryToDecimal(test)}"));

Console.Write(report);

输出:

         0 => 0
        -0 => 0
       100 => 4
      -100 => -4
       10. => 2
      -10. => -2
       1.1 => 1.5
   101.101 => 5.625
  -101.101 => -5.625
     .1011 => 0.6875
   -.11011 => -0.84375
    100.00 => 4
         . => 0  
© www.soinside.com 2019 - 2024. All rights reserved.