23

我有一个 14 个字符的字符串。这是 7 个字节的十六进制表示。我想将其转换为二进制。我尝试使用Convert.ToString(Convert.ToInt32(hexstring, 16), 2);对于小字符串,这有效,但对于 14 个字符,它不起作用,因为结果太大。我该如何管理?请记住,转换的输出应该是长度为 56 个字符的二进制字符串(我们必须保留前导零)。(例如(字节)0x01 的转换应该产生“00000001”而不是“1”)

4

8 回答 8

38

您可以将每个十六进制数字转换为四个二进制数字:

string binarystring = String.Join(String.Empty,
  hexstring.Select(
    c => Convert.ToString(Convert.ToInt32(c.ToString(), 16), 2).PadLeft(4, '0')
  )
);

你需要一个using System.Linq;文件的顶部才能工作。

于 2011-07-07T21:28:11.283 回答
12
Convert.ToString(Convert.ToInt64(hexstring, 16), 2);

也许?或者

Convert.ToString(Convert.ToInt64(hexstring, 16), 2).PadLeft(56, '0');
于 2011-07-07T21:23:36.007 回答
12

为什么不采用简单的方法并定义自己的映射?

private static readonly Dictionary<char, string> hexCharacterToBinary = new Dictionary<char, string> {
    { '0', "0000" },
    { '1', "0001" },
    { '2', "0010" },
    { '3', "0011" },
    { '4', "0100" },
    { '5', "0101" },
    { '6', "0110" },
    { '7', "0111" },
    { '8', "1000" },
    { '9', "1001" },
    { 'a', "1010" },
    { 'b', "1011" },
    { 'c', "1100" },
    { 'd', "1101" },
    { 'e', "1110" },
    { 'f', "1111" }
};

public string HexStringToBinary(string hex) {
    StringBuilder result = new StringBuilder();
    foreach (char c in hex) {
        // This will crash for non-hex characters. You might want to handle that differently.
        result.Append(hexCharacterToBinary[char.ToLower(c)]);
    }
    return result.ToString();
}

请注意,这将保持前导零。so"aa"将转换为"10101010"while"00000aa"将转换为"0000000000000000000010101010".

于 2011-07-07T21:57:28.207 回答
4

我的 C++ 背景答案:

private Byte[] HexToBin(string pHexString)
{
    if (String.IsNullOrEmpty(pHexString))
        return new Byte[0];

    if (pHexString.Length % 2 != 0)
        throw new Exception("Hexstring must have an even length");

    Byte[] bin = new Byte[pHexString.Length / 2];
    int o = 0;
    int i = 0;
    for (; i < pHexString.Length; i += 2, o++)
    {
        switch (pHexString[i])
        {
            case '0': bin[o] = 0x00; break;
            case '1': bin[o] = 0x10; break;
            case '2': bin[o] = 0x20; break;
            case '3': bin[o] = 0x30; break;
            case '4': bin[o] = 0x40; break;
            case '5': bin[o] = 0x50; break;
            case '6': bin[o] = 0x60; break;
            case '7': bin[o] = 0x70; break;
            case '8': bin[o] = 0x80; break;
            case '9': bin[o] = 0x90; break;
            case 'A':
            case 'a': bin[o] = 0xa0; break;
            case 'B':
            case 'b': bin[o] = 0xb0; break;
            case 'C':
            case 'c': bin[o] = 0xc0; break;
            case 'D':
            case 'd': bin[o] = 0xd0; break;
            case 'E':
            case 'e': bin[o] = 0xe0; break;
            case 'F':
            case 'f': bin[o] = 0xf0; break;
            default: throw new Exception("Invalid character found during hex decode");
        }

        switch (pHexString[i+1])
        {
            case '0': bin[o] |= 0x00; break;
            case '1': bin[o] |= 0x01; break;
            case '2': bin[o] |= 0x02; break;
            case '3': bin[o] |= 0x03; break;
            case '4': bin[o] |= 0x04; break;
            case '5': bin[o] |= 0x05; break;
            case '6': bin[o] |= 0x06; break;
            case '7': bin[o] |= 0x07; break;
            case '8': bin[o] |= 0x08; break;
            case '9': bin[o] |= 0x09; break;
            case 'A':
            case 'a': bin[o] |= 0x0a; break;
            case 'B':
            case 'b': bin[o] |= 0x0b; break;
            case 'C':
            case 'c': bin[o] |= 0x0c; break;
            case 'D':
            case 'd': bin[o] |= 0x0d; break;
            case 'E':
            case 'e': bin[o] |= 0x0e; break;
            case 'F':
            case 'f': bin[o] |= 0x0f; break;
            default: throw new Exception("Invalid character found during hex decode");
        }
    }
    return bin;
}
于 2013-09-04T09:58:24.760 回答
4

您可以使用此代码从十六进制字符串中获取字节数组

 public static byte[] StringToByteArray(String hex)
    {
        int NumberChars = hex.Length;
        byte[] bytes = new byte[NumberChars / 2];
        for (int i = 0; i < NumberChars; i += 2)
            bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
        return bytes;
    }
于 2018-03-28T21:49:44.683 回答
0

如果一次转换一个字符怎么办?我无法对此进行测试,但这个想法应该可行。

//Convert.ToString(Convert.ToInt32(hexstring, 16), 2)

StringBuilder sb = new StringBuilder();
foreach( char c in hexstring.ToCharArray() ){
  sb.Append( Convert.ToString(Convert.ToInt32(c.ToString(), 16), 2);
}
于 2011-07-07T21:28:39.007 回答
0

You can do this.

I have put it in a class called UtilMath this is a good Idea as, if you ever use it in a different program you can use the class again. And as the name implies this is for all my Math functions.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Math.Util
{
    class UtilMath
    {

        public static string hex2binary(string hexvalue)
        {
            // Convert.ToUInt32 this is an unsigned int
            // so no negative numbers but it gives you one more bit
            // it much of a muchness 
            // Uint MAX is 4,294,967,295 and MIN is 0
            // this padds to 4 bits so 0x5 = "0101"
            return String.Join(String.Empty, hexvalue.Select(c => Convert.ToString(Convert.ToUInt32(c.ToString(), 16), 2).PadLeft(4, '0')));
        }
    }
}

now before you use it you need to include it,

using Math.Util

then if you need to use it you can call it by going

UtilMath.hex2binary("FF");

Or

String hexString = "FF";
UtilMath.hex2binary(hexString);

Hope this helps.

于 2012-05-09T03:01:01.237 回答
0

Convert.FromHexString已在 .Net 5 中引入

 var bytes = Convert.FromHexString("13AF3F")
于 2021-12-18T05:37:00.400 回答