【问题标题】:How to convert a String to a Hex Byte Array? [duplicate]如何将字符串转换为十六进制字节数组? [复制]
【发布时间】:2011-02-27 15:55:33
【问题描述】:

可能重复:
How do you convert Byte Array to Hexadecimal String, and vice versa, in C#?

为了测试我的加密算法,我得到了密钥、纯文本及其生成的密文。

密钥和明文都在字符串中

如何将其转换为十六进制字节数组??

类似这样的东西:E8E9EAEBEDEEEFF0F2F3F4F5F7F8F9FA

到这样的事情:

byte[] key = new byte[16] { 0xE8, 0xE9, 0xEA, 0xEB, 0xED, 0xEE, 0xEF, 0xF0, 0xF2, 0xF3, 0xF4, 0xF5, 0xF7, 0xF8, 0xF9, 0xFA} ;

提前感谢:)

【问题讨论】:

标签: c# arrays bytearray hex


【解决方案1】:

Do you need this?

static class HexStringConverter
{
    public static byte[] ToByteArray(String HexString)
    {
        int NumberChars = HexString.Length;
        byte[] bytes = new byte[NumberChars / 2];
        for (int i = 0; i < NumberChars; i += 2)
        {
            bytes[i / 2] = Convert.ToByte(HexString.Substring(i, 2), 16);
        }
        return bytes;
    }
}

希望对你有帮助。

【讨论】:

    【解决方案2】:

    来自MSDN的示例代码:

    string hexValues = "48 65 6C 6C 6F 20 57 6F 72 6C 64 21";
    string[] hexValuesSplit = hexValues.Split(' ');
    foreach (String hex in hexValuesSplit)
    {
        // Convert the number expressed in base-16 to an integer.
        int value = Convert.ToInt32(hex, 16);
        // Get the character corresponding to the integral value.
        string stringValue = Char.ConvertFromUtf32(value);
        char charValue = (char)value;
        Console.WriteLine("hexadecimal value = {0}, int value = {1}, char value = {2} or {3}", hex, value, stringValue, charValue);
    }
    

    您只需更改它以将字符串拆分为每 2 个字符而不是空格。

    【讨论】:

      【解决方案3】:

      你是不是这个意思

      StringBuilder Result = new StringBuilder();
          string HexAlphabet = "0123456789ABCDEF";
      
          foreach (byte B in Bytes)
              {
              Result.Append(HexAlphabet[(int)(B >> 4)]);
              Result.Append(HexAlphabet[(int)(B & 0xF)]);
              }
      
          return Result.ToString();
      

      【讨论】:

        猜你喜欢
        • 2018-05-09
        • 2010-09-24
        • 2017-08-23
        • 2013-01-14
        • 1970-01-01
        • 2021-10-31
        • 2019-02-12
        相关资源
        最近更新 更多