Apache.Shiro.Codec.Hex.FromHexString C# (CSharp) Method

FromHexString() public static method

public static FromHexString ( string value ) : byte[]
value string
return byte[]
        public static byte[] FromHexString(string value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            int length = value.Length;
            if (length % 2 == 1)
            {
                throw new ArgumentException(Properties.Resources.HexCharArrayOddLengthMessage);
            }

            byte[] bytes = new byte[length / 2];
            for (int i = 0, j = 0; j < length; j += 2, ++i)
            {
                bytes[i] = Convert.ToByte(value.Substring(j, 2), 16);
            }

            return bytes;
        }

Usage Example

Example #1
0
        public void TestFromHexString()
        {
            var expectedBytes = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
            var actualBytes   = Hex.FromHexString("000102030405060708090A0B0C0D0E0F");

            Assert.NotNull(actualBytes);
            Assert.AreEqual(expectedBytes.Length, actualBytes.Length);

            for (var i = 0; i < expectedBytes.Length; ++i)
            {
                Assert.AreEqual(expectedBytes[i], actualBytes[i]);
            }
        }