-8

请帮助我希望 c# 提出这个问题

请输入一个 7 位二进制数:

0010011

您带有奇偶校验位的号码是:

00100111 

这是我想出的代码,它可能是错误的,请你纠正它,这样好吗?

{
   Console.WriteLine("Please enter a 7- bit binary number");

   string number = Console.ReadLine();

   int count1 = 0;
   int count2 = 0;

   for(int i = 0; i < number.Length; i++)
   {
      count1++;
   }
   else 
   {
       count2++;
   }

   if (count1 < count2) 
      Console.WriteLine("Your number with parity bit is "+ number+ "1");
}
else
{ 
    Console.WriteLine("Your number with parity bit is "+ number + "0");
}

    }
}

}

提前谢谢帮助

4

3 回答 3

1

算法:

  1. 将字符串转换为整数。
  2. 找到奇偶校验位值。
  3. 将奇偶校验位值“附加”到源整数 => 结果整数。
  4. 将结果整数转换为字符串并将字符串写入输出。

源代码:

Console.Write("Please enter a 7-bit binary number: ");
string numberString = Console.ReadLine();

// Convert to integer representation.
int number = Convert.ToInt32(numberString, 2);

// Find parity bit value for the integer.
bool parity = false;
int tempNumber = number;
while (tempNumber > 0)
{
    parity ^= tempNumber % 2 != 0;
    tempNumber >>= 1;
}

// "Append" parity bit.
int numberWithParity = number << 1 | (parity ? 1 : 0);

// Convert the result to string representation.
numberString = Convert.ToString(numberWithParity, 2).PadLeft(8, '0');
Console.WriteLine("Your number with parity bit is {0}", numberString);
于 2013-02-11T17:51:01.460 回答
1

这应该这样做:

Console.WriteLine("Please enter a 7- bit binary number");

string number = Console.ReadLine();

int count = 0;

for(int i = 0; i < number.Length; i++)
{
   if(number[i] == '1')
   {
      count++;
   }
}

Console.WriteLine("Your number with parity bit is "+ number + (count % 2).ToString());

我想这超出了您当前的水平,但这也应该有效:

Console.WriteLine("Please enter a 7- bit binary number");

string number = Console.ReadLine();

string parityBit = (number.Where(c => c == '1').Count() % 2).ToString();

Console.WriteLine("Your number with parity bit is "+ number + parityBit);
于 2013-02-11T17:31:03.550 回答
1

因此,奇偶校验位指示输入是否具有偶数个一位。所以如果你的输入字符串是二进制的(你通常不应该安全地假设,但我们现在将忽略它),你需要简单地计算1二进制字符串中 s 的数量。

按照您最初的想法(我认为?),您可以这样做:

int numberOfOnes = 0;
for (int i = 0; i < bitstring.length; i++)
{
    if (bitstring[i] == '1')
        numberOfOnes++;
}

if (numbersOfOnes % 2 == 0)
    // even number of ones
else
    // uneven number of ones

请注意,奇偶校验位有两种不同的版本,具体取决于您是否具有1奇偶校验是否为偶数或0奇偶校验是否为偶数。你选择哪一个取决于你。

于 2013-02-11T17:35:26.170 回答