using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; public class Test { public static void Main() { //原始資料 string byteArrayString = "FF0133000104D2EA4104418501050C1E01010001"; byte[] byteArrayInput = ConvertHexStringToByteArray(byteArrayString); BitArray result = new BitArray(byteArrayInput.Length); //取前2 xor char[] strArray = byteArrayString.ToCharArray(); for (int i = 0; i < strArray.Length; i=i+2) { //測試用,先不判斷長度 try { string inputA = string.Format("{0}{1}", strArray[i], strArray[i + 1]); string inputB = string.Format("{0}{1}", strArray[i + 2], strArray[i + 3]); if (i == 0) { BitArray input1 = new BitArray(ConvertHexStringToByteArray(inputA)); BitArray input2 = new BitArray(ConvertHexStringToByteArray(inputB)); Console.WriteLine(inputA + "^" + inputB); result = input1.Xor(input2); } else { BitArray input1 = result; BitArray input2 = new BitArray(ConvertHexStringToByteArray(inputB)); Console.WriteLine(inputA + "^" + inputB); result = input1.Xor(input2); } } catch(Exception ex) { Console.WriteLine(ex.Message); } } byte[] output = new byte[result.Length]; result.CopyTo(output,0); Console.WriteLine(BitConverter.ToString(output)); Console.WriteLine(BitConverter.ToInt32(output,0)); Console.ReadLine(); //Pause } public static string ByteArrayToString(byte[] ba) { string hex = BitConverter.ToString(ba); return hex.Replace("-", ""); } /// /// Shifts the bits in an array of bytes to the left. /// /// The byte array to shift. public static bool ShiftLeft(byte[] bytes) { bool leftMostCarryFlag = false; // Iterate through the elements of the array from left to right. for (int index = 0; index < bytes.Length; index++) { // If the leftmost bit of the current byte is 1 then we have a carry. bool carryFlag = (bytes[index] & 0x80) > 0; if (index > 0) { if (carryFlag == true) { // Apply the carry to the rightmost bit of the current bytes neighbor to the left. bytes[index - 1] = (byte)(bytes[index - 1] | 0x01); } } else { leftMostCarryFlag = carryFlag; } bytes[index] = (byte)(bytes[index] << 1); } return leftMostCarryFlag; } private static byte[] ConvertHexStringToByteArray(string hexString) { if (hexString.Length % 2 != 0) { throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "The binary key cannot have an odd number of digits: {0}", hexString)); } byte[] HexAsBytes = new byte[hexString.Length / 2]; for (int index = 0; index < HexAsBytes.Length; index++) { string byteValue = hexString.Substring(index * 2, 2); HexAsBytes[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture); } return HexAsBytes; } }