示例: 判断二进制串的奇偶性
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test6
{
class Program
{
static void Main(string[] args)
{
string b = "111101";
int d = Convert.ToInt32(b, 2);
Console.WriteLine("二进制 {0} 十进制 {1} 奇偶性 {2}", b, d, CheckParity(d));
b = "111001";
d = Convert.ToInt32(b, 2);
Console.WriteLine("二进制 {0} 十进制 {1} 奇偶性 {2}", b, d, CheckParity(d));
Console.Read();
}
public static int CheckParity(int x)
{
/**
奇偶校验方法:
二进制串中的每一位从左到右依次异或,因为异或满足结合律,可以用下面方法进行计算。
**/
//相邻位异或
int y;
y = x ^ (x >> 1);
y = y ^ (y >> 2);
y = y ^ (y >> 4);
y = y ^ (y >> 8);
y = y ^ (y >> 16);
y &= 1;//最后一位决定了奇偶性(1:奇 0:偶)
//y的第几位的奇偶性决定了最左边到此位置二进制串的奇偶性
//如: y&2 代表了左边31位的奇偶性
//如: y&4 代表了左边30位的奇偶性
return y;
}
public static int CheckParity(byte x)
{
int y;
y = x ^ (x >> 1);
y = y ^ (y >> 2);
y = y ^ (y >> 4);
y &= 1;
return y;
}
}
}
运行测试