Example #1
0
 /// <summary>
 /// Add the content of the given writer to the writer
 /// </summary>
 /// <param name="writer"></param>
 /// <remarks>
 /// This functionality is not allowed when the writer has been sealed
 /// </remarks>
 public void WriteBytes(ByteArrayWriter writer)
 {
     this.WriteBytes(
         writer._buffer,
         0,
         writer._length);
 }
Example #2
0
        /// <summary>
        /// Parse a string containing an HEX representation to a byte-array
        /// </summary>
        /// <param name="source">The source string containing HEX characters.</param>
        /// <returns>The resulting byte-array</returns>
        /// <remarks>
        ///     <para>The conversion does not care about character casing.</para>
        ///     <para>Any character off the HEX-set is treated as separator.</para>
        ///     <para>The HEX-chars can be even without any separator (i.e. packed),
        ///     however the conversion consider character pairs.</para>
        /// </remarks>
        /// <example>Sample behavior of the conversion:
        ///     <code>
        ///     byte[] b = ByteArrayHelpers.FromHex("0 zz@ q1 23 04 567 8! 9 abcdef");
        ///
        ///     for (int i = 0; i &lt; b.Length; i++)
        ///     {
        ///         Console.Write(b[i].ToString() + " ");
        ///     }
        ///     Console.WriteLine();
        ///
        ///     </code>
        ///     Yields the result:
        ///     <code>
        ///     0 1 35 4 86 7 8 9 171 205 239
        ///     </code>
        /// </example>
        /// <seealso cref="ToHex"/>
        public static byte[] FromHex(string source)
        {
            if (_tblfromhex == null)
            {
                InitFromHexConverter();
            }

            //create a string reader to consume input chars
            var reader = new SimpleStringReader(source);

            //create a writer to accumulate the resulting bytes
            var writer = new ByteArrayWriter();

            //consume characters until the end of string
            int nibble = 0;
            int digit  = 0;
            int code;

            while ((code = reader.GetNext()) >= 0)
            {
                if (code > 0)
                {
                    digit = (digit << 8) | (code - 1);
                    nibble++;
                }
                else if (nibble > 0)
                {
                    nibble = 2;
                }

                if (nibble == 2)
                {
                    writer.WriteByte((byte)digit);
                    digit  = 0;
                    nibble = 0;
                }
            }

            return(writer.ToByteArray());
        }