可能重复:
如何在7位二进制数上添加偶校验位
这是我的新代码,它将7位二进制数转换为具有偶校验的8位.但它不起作用.例如,当我输入0101010时,它表示偶数奇偶校验的数字是147.你能帮忙,告诉我有什么问题吗?
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter a 7-bit binary number:");
int a = Convert.ToInt32(Console.ReadLine());
byte[] numberAsByte = new byte[] { (byte)a };
System.Collections.BitArray bits = new System.Collections.BitArray(numberAsByte);
a = a << 1;
int count = 0;
for (int i = 0; i < 8; i++)
{
if (bits[i])
{
count++;
}
if (count % 2 == 1)
{
bits[7] = true;
}
bits.CopyTo(numberAsByte, 0);
a = numberAsByte[0];
Console.WriteLine("The number with an even parity bit is:");
Console.Write(a);
Console.ReadLine();
}
}
Run Code Online (Sandbox Code Playgroud)
}
对从Console.ReadLine()获得的内容使用int.TryParse().然后,您需要检查该数字是否在0到127之间,以确保它仅使用7位.然后,您需要计算数字的二进制表示中的1的数量.并在数字上加128以设置奇偶校验位,具体取决于您是指定奇数还是偶数奇偶校验.
计数1是你真正的家庭作业.
| 归档时间: |
|
| 查看次数: |
5756 次 |
| 最近记录: |