请帮助我希望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");
}
}
}
}
提前帮助
答案 0 :(得分: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);
答案 1 :(得分:1)
因此,parity bit表示输入是否具有偶数个1位。因此,如果您的输入字符串是二进制的(通常您不应该安全地假设,但我们现在将忽略它),您只需要计算二进制字符串中1
的数量。
按照你最初的想法(我想?),你可以这样做:
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
。你选择哪一个取决于你。
答案 2 :(得分:1)
算法:
源代码:
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);