可能重复: 如何在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();
}
}}
发布于 2012-02-05 19:36:42
对从int.TryParse()获得的信息使用Console.ReadLine()。然后,您需要检查数字在0到127之间,以确保它只使用7位。然后,您需要计算数字的二进制表示中的1s数。并将128添加到数字中以设置奇偶校验位,这取决于您指定的奇偶校验。
数1s是你真正的家庭作业。
发布于 2012-02-05 19:42:34
通过使用BitArray类,您可以编写
int a = Convert.ToInt32(Console.ReadLine());
byte[] numberAsByte = new byte[] { (byte)a };
BitArray bits = new BitArray(numberAsByte);这会将字节的单个位转换为BitArray,它表示可以轻松处理的布尔值数组。注意,BitArray的构造函数接受一个字节数组。因为我们只有一个字节,所以我们必须传递一个长度为1的字节数组,其中包含这个单字节(numberAsByte)。
现在让我们数一数所设置的位数。
int count = 0;
for (int i = 0; i < 8; i++) {
if (bits[i]) {
count++;
}
}注意,我们只是使用bits[i]进行了一点测试,这会产生一个布尔值。测试bits[i] == true是完全合法和正确的,得到了同样的结果,但是不必要的复杂。if语句不需要比较。它只需要一个布尔值。
这将计算奇偶校验位。
if (count % 2 == 1) { // Odd number of bits
bits[7] = true; // Set the left most bit as parity bit for even parity.
}%运算符是模运算符。它产生整数除法的其余部分。如果x % 2是偶数的话,0就会产生。如果您想要奇数奇偶校验位,则可以测试count % 2 == 0。
BitArray有一个CopyTo方法,它将我们的位转换回字节数组(在本例中只包含一个字节)。
bits.CopyTo(numberAsByte, 0);
a = numberAsByte[0];numberAsByte[0]包含带有奇偶校验位的数字。
如果你想要右边的奇偶位,那么你必须先把这个数字向左移动一位。
int a = Convert.ToInt32(Console.ReadLine());
a = a << 1;
// Do the parity bit calculation as above and, if necessary
// set the right most bit as parity bit.
bits[0] = true;发布于 2012-02-05 19:34:13
根据维基百科,奇偶校验位有两种变化,所以我实现了参数来选择所需的参数。它支持用户输入多达63位,我把验证代码的实现留给您。
ulong GetNumberParity(string input, bool isEvenParity)
{
ulong tmp = Convert.ToUInt64(input, 2);
ulong c = 0;
for (int i = 0; i < 64; i++) c += tmp >> i & 1;
if(isEvenParity)
return Convert.ToUInt64((c % 2 != 0 ? "1" : "0") + input, 2);
else
return Convert.ToUInt64((c % 2 == 0? "1" : "0") + input, 2);
}https://stackoverflow.com/questions/9152125
复制相似问题