HEX Convert
2018-09-12

0X1 摘要

string convert-to hex and hex convert-to string

0X2 WHY

  • Base64中存在不安全的字符+,=,/
  • 那么有没有一种只由字母和数字构成的密文方式呢
  • 缺点 字节数由1.5倍变成2倍

0X3 源

反射mscorlib 下System.BitConverter类

private static char GetHexValue(int i)
{
    if (i < 10)
    {
        return (char)(i + 48);
    }
    return (char)(i - 10 + 65);
}
///<summary>将字节的指定子数组的每个元素的数值转换为其等效的十六进制字符串表示形式</summary>
public static string ToString(byte[] value, int startIndex, int length)
{
    if (value == null)
    {
        throw new ArgumentNullException("value");
    }
    if (startIndex < 0 || (startIndex >= value.Length && startIndex > 0))
    {
        throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
    }
    if (length < 0)
    {
        throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
    }
    if (startIndex > value.Length - length)
    {
        throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall"));
    }
    if (length == 0)
    {
        return string.Empty;
    }
    if (length > 715827882)
    {
        throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_LengthTooLarge", new object[]
        {
            715827882
        }));
    }
    int num = length * 3;
    char[] array = new char[num];
    int num2 = startIndex;
    for (int i = 0; i < num; i += 3)
    {
        byte b = value[num2++];
        array[i] = BitConverter.GetHexValue((int)(b / 16));
        array[i + 1] = BitConverter.GetHexValue((int)(b % 16));
        array[i + 2] = '-';
    }
    return new string(array, 0, array.Length - 1);
}

0X4 改造

private static char _hexValue(int i) => (i < 10) ? (char)(i + 48) : (char)(i + 55);

/// <summary>转为HEXstring</summary>  
public static string HexFormat(byte[] input)
{
    int num = input.Length << 1;
    char[] array = new char[num];
    for (int i = 0; i < num; i += 2)
    {
        byte temp = input[i >> 1];
        array[i] = _hexValue(temp >> 4);
        array[i + 1] = _hexValue(temp & 15);
    }
    return new string(array);
}

/// <summary>从HEXstring转为字节</summary>  
public static byte[] HexFormat(string input)
{
    var length = input.Length;
    if ((length & 1) != 0) throw new ArgumentException("format error");
    byte[] result = new byte[length >> 1];
    for (int i = 0; i < result.Length; i++)
        result[i] = byte.Parse(input.Substring(i << 1, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
    return result;
}