예제 #1
0
        /// <summary>
        /// Create a <see cref="BitString"/> using MSB hex.
        /// </summary>
        /// <param name="hexMSB">The MSB hexadecimal string</param>
        /// <param name="bitLength">The length of the resulting <see cref="BitString"/> by taking that amount of MSBs</param>
        /// <param name="truncateBitsFromEndOfLastByte">When the bitLength is not a multiple of 8, the hex needs to be truncated in the last byte. This parameter determines which side of the last byte is truncated</param>
        public BitString(string hexMSB, int bitLength = -1, bool truncateBitsFromEndOfLastByte = true)
        {
            if (string.IsNullOrEmpty(hexMSB) || bitLength == 0)
            {
                _bits = new BitArray(0);
                return;
            }

            hexMSB = hexMSB.Replace(" ", "");
            int numberChars = hexMSB.Length;

            if (numberChars % 2 != 0)
            {
                throw new InvalidBitStringLengthException($"{nameof(BitString)}s are expected to have an even number of hex characters. Value was \"{hexMSB}\".");
            }

            byte[] bytesInMSB = new byte[numberChars / 2];
            for (int i = 0; i < numberChars; i += 2)
            {
                bytesInMSB[i / 2] = Convert.ToByte(hexMSB.Substring(i, 2), 16);
            }

            if (bitLength < 0)
            {
                _bits = Helper.MostSignificantByteArrayToLeastSignificantBitArray(bytesInMSB);
            }
            else
            {
                var bitsNeeded = System.Math.Min(bitLength, numberChars * BITSINBYTE / 2);

                var bitsInMSB     = Helper.MostSignificantByteArrayToMostSignificantBitArray(bytesInMSB);
                var truncatedBits = new BitArray(bitsNeeded);

                if (truncateBitsFromEndOfLastByte)
                {
                    for (var i = 0; i < bitsNeeded; i++)
                    {
                        truncatedBits[i] = bitsInMSB[i];
                    }
                }
                else
                {
                    var firstBits = bitsNeeded - (bitsNeeded % 8);
                    for (var i = 0; i < firstBits; i++)
                    {
                        truncatedBits[i] = bitsInMSB[i];
                    }

                    var skippedBits = (bytesInMSB.Length * BITSINBYTE) - bitsNeeded;
                    for (var i = firstBits; i < bitsNeeded; i++)
                    {
                        truncatedBits[i] = bitsInMSB[i + skippedBits];
                    }
                }

                _bits = Helper.ReverseBitArrayBits(truncatedBits);
            }
        }
예제 #2
0
 public static BitArray Reverse(this BitArray bArray)
 {
     return(MsbLsbConversionHelpers.ReverseBitArrayBits(bArray));
 }