C# 字节数组 二进制和16进制互转

    public static bool[] HexToBoolBinary(byte[] hexBytes)
    {
        byte[] binaryBytes = new byte[hexBytes.Length * 8];
        bool[] res = new bool[hexBytes.Length * 8];

        for (int i = 0; i < hexBytes.Length; i++)
        {
            byte hexByte = hexBytes[i];

            for (int j = 0; j < 8; j++)
            {
                byte binaryBit = (byte)((hexByte >> (7 - j)) & 1);
                binaryBytes[i * 8 + j] = binaryBit;
                res[i * 8 + j] = binaryBit == 0 ? false : true;
            }
        }
        return res;
    }

    public static byte[] BinaryToHex(byte[] binaryBytes)
    {
        int hexLength = binaryBytes.Length / 8;
        byte[] hexBytes = new byte[hexLength];

        for (int i = 0; i < hexLength; i++)
        {
            byte hexByte = 0;

            for (int j = 0; j < 8; j++)
            {
                byte binaryBit = binaryBytes[i * 8 + j];
                hexByte = (byte)((hexByte << 1) | binaryBit);
            }

            hexBytes[i] = hexByte;
        }

        return hexBytes;
    }

你可能感兴趣的:(C#,c#,算法)