如何增加偶校验位7位二进制数 [英] How to add even parity bit on 7-bit binary number
问题描述
我从我刚才的问题继续进行。我正在那里用户输入一个7位二进制数和计算机打印出的数量为偶数的奇偶校验位的数量的权利C#程序。我挣扎。我有一个代码,但它说BitArray是一个命名空间,但作为一个类型。此外,有没有一种方法,我可以改进的代码,使它更容易?
命名空间BitArray
{
类项目
{
静态无效的主要(字串[] args)
{
Console.WriteLine(请输入7位二进制数:);
INT A = Convert.ToInt32(到Console.ReadLine());
字节[] = numberAsByte新的字节[] {(字节)一};
BitArray位=新BitArray(numberAsByte);
诠释计数= 0;
的for(int i = 0; I< 8;我++)
{
如果(位[I])
{
计数++;
}
}
如果(计数%2 == 1)
{
比特[7] =真;
}
bits.CopyTo(numberAsByte,0);
A = numberAsByte [0];
Console.WriteLine(带奇偶校验位的二进制数是:);
Console.WriteLine(一);
可能是重复的,他们使用的电路更有趣做到这一点..
布尔奇= FALSE;
的for(int i = 6; I> = 0;我 - )
奇^ =(号及(1 LT;< I))> 0;如果你想偶校验设置7位奇,奇校验不奇怪
然后
或
布尔甚= TRUE;
的for(int i = 6; I> = 0;我 - )
连^ =(号及(1 LT;< I))> 0;
的电路是双重函数返回0和1或1和0,不超过1比特以时间为好,但这是TPL有点光......
PS你可能要检查的输入< 128,否则一切都将顺利错了。
户外没有注意到的功课标签,不使用,除非你能解释一下。
I am continuing from my previous question. I am making a c# program where the user enters a 7-bit binary number and the computer prints out the number with an even parity bit to the right of the number. I am struggling. I have a code, but it says BitArray is a namespace but is used as a type. Also, is there a way I could improve the code and make it simpler?
namespace BitArray
{
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 };
BitArray bits = new BitArray(numberAsByte);
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 binary number with a parity bit is:");
Console.WriteLine(a);
Might be more fun to duplicate the circuit they use to do this..
bool odd = false;
for(int i=6;i>=0;i--)
odd ^= (number & (1 << i)) > 0;
Then if you want even parity set bit 7 to odd, odd parity to not odd.
or
bool even = true;
for(int i=6;i>=0;i--)
even ^= (number & (1 << i)) > 0;
The circuit is dual function returns 0 and 1 or 1 and 0, does more than 1 bit at a time as well, but this is a bit light for TPL....
PS you might want to check the input for < 128 otherwise things are going to go well wrong.
ooh didn't notice the homework tag, don't use this unless you can explain it.
这篇关于如何增加偶校验位7位二进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!