예제 #1
0
        /// <summary>
        /// Converts the members of the bit field to an integer value.
        /// </summary>
        /// <param name="obj">An instance of a struct that implements the interface IBitField.</param>
        /// <returns>An integer representation of the bit field.</returns>
        public static ulong ToUInt64(this IBitField obj)
        {
            ulong result = 0;

            // Loop through all the properties
            foreach (PropertyInfo pi in obj.GetType().GetProperties())
            {
                // Check if the property has an attribute of type BitFieldLengthAttribute
                BitFieldInfoAttribute bitField = (pi.GetCustomAttribute(typeof(BitFieldInfoAttribute)) as BitFieldInfoAttribute);
                if (bitField != null)
                {
                    // Calculate a bitmask using the length of the bit field
                    ulong mask = 0;
                    for (byte i = 0; i < bitField.Length; i++)
                    {
                        mask |= 1UL << i;
                    }

                    // This conversion makes it possible to use different types in the bit field
                    ulong value = Convert.ToUInt64(pi.GetValue(obj));

                    result |= (value & mask) << bitField.Offset;
                }
            }

            return(result);
        }
예제 #2
0
        /// <summary>
        /// This method converts the struct into a string of binary values.
        /// The length of the string will be equal to the number of bits in the struct
        /// The least significant bit will be on the right in the string.
        /// </summary>
        /// <param name="obj">An instance of a struct that implements the interface IBitField.</param>
        /// <returns>A string representing the binary value of tbe bit field.</returns>
        public static string ToBinaryString(this IBitField obj)
        {
            BitFieldNumberOfBitsAttribute bitField = (obj.GetType().GetCustomAttribute(typeof(BitFieldNumberOfBitsAttribute)) as BitFieldNumberOfBitsAttribute);

            if (bitField == null)
            {
                throw new Exception(string.Format("The attribute 'BitFieldNumberOfBitsAttribute' has to be added to the struct '{0}'.", obj.GetType().Name));
            }

            StringBuilder sb = new StringBuilder(bitField.BitCount);

            ulong bitFieldValue = obj.ToUInt64();

            for (int i = bitField.BitCount - 1; i >= 0; i--)
            {
                sb.Append(((bitFieldValue & (1UL << i)) > 0) ? "1" : "0");
            }

            return(sb.ToString());
        }