C# 如何将大的十六进制字符串转换为二进制

发布于 2024-11-19 00:37:57 字数 246 浏览 4 评论 0原文

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

I have a string with 14 characters . This is a hex represantation of 7bytes. I want to convert it to binary. I tried using Convert.ToString(Convert.ToInt32(hexstring, 16), 2); For small strings this works but for 14 characters it will not work because the result is too large.
How can i manage this? Keep in mind that the output of the conversion should be a binary string with a lengeth of 56 characters (we must keep the leading zeros). (e.g. conversion of (byte)0x01 should yield "00000001" rather than "1")

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

你穿错了嫁妆 2024-11-26 00:37:57

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

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

您需要在文件顶部添加 using System.Linq; 才能使其正常工作。

You can just convert each hexadecimal digit into four binary digits:

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

You need a using System.Linq; a the top of the file for this to work.

随遇而安 2024-11-26 00:37:57
Convert.ToString(Convert.ToInt64(hexstring, 16), 2);

或许?或者

Convert.ToString(Convert.ToInt64(hexstring, 16), 2).PadLeft(56, '0');
Convert.ToString(Convert.ToInt64(hexstring, 16), 2);

Maybe? Or

Convert.ToString(Convert.ToInt64(hexstring, 16), 2).PadLeft(56, '0');
兰花执着 2024-11-26 00:37:57

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

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();
}

请注意,这将保留前导零。因此,"aa" 将转换为 "10101010",而 "00000aa" 将转换为 "0000000000000000000010101010"

Why not just take the simple approach and define your own mapping?

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();
}

Note that this will keep leading zeros. So "aa" would be converted to "10101010" while "00000aa" would be converted to "0000000000000000000010101010".

棒棒糖 2024-11-26 00:37:57

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

 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;
    }

You can get a byte array from hex string using this code

 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;
    }
救星 2024-11-26 00:37:57

Convert.FromHexString已在.Net 5中引入

 var bytes = Convert.FromHexString("13AF3F")

Convert.FromHexString has been introduced in .Net 5

 var bytes = Convert.FromHexString("13AF3F")
烈酒灼喉 2024-11-26 00:37:57

我的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;
}

My C++ background answer:

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;
}
空气里的味道 2024-11-26 00:37:57

你可以这样做。

我把它放在一个名为 UtilMath 的类中
这是一个好主意,因为如果您在不同的程序中使用它,您可以再次使用该类。
顾名思义,这适用于我所有的数学函数。

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')));
        }
    }
}

现在,在使用它之前,您需要包含它,

using Math.Util

然后如果您需要使用它,您可以通过“

UtilMath.hex2binary("FF");

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

希望这有帮助”来调用它。

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.

早乙女 2024-11-26 00:37:57

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

//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);
}

What if you convert one character at a time? I'm can't test this out, but the idea should work.

//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);
}
美人骨 2024-11-26 00:37:57

使用 Int64 而不是 Int32 怎么样?

Convert.ToString(Convert.ToInt64(hexstring, 16), 2);

How about using Int64 instead of Int32?

Convert.ToString(Convert.ToInt64(hexstring, 16), 2);
强者自强 2024-11-26 00:37:57

如果你需要一个字节数组,你可以通过以下方式获取:

Collection<byte> bytes = new Collection<byte>();
for (int i = 0; i < hexText.Length; i += 2) {
    byte bin = BitConverter.GetBytes(Convert.ToInt32(hexText.Substring(i, 2), 16))[0];
    bytes.Add(bin);
}

但如果是直接保存到文件,我会直接这样做:

using FileStream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write);
for (int i = 0; i < hexText.Length; i += 2) {
    byte bin = BitConverter.GetBytes(Convert.ToInt32(hexText.Substring(i, 2), 16))[0];
    fileStream.WriteByte(bin);
}
fileStream.Close();

If you need a byte array, you can get it by:

Collection<byte> bytes = new Collection<byte>();
for (int i = 0; i < hexText.Length; i += 2) {
    byte bin = BitConverter.GetBytes(Convert.ToInt32(hexText.Substring(i, 2), 16))[0];
    bytes.Add(bin);
}

But if it is directly to save to a file, I would do it directly:

using FileStream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write);
for (int i = 0; i < hexText.Length; i += 2) {
    byte bin = BitConverter.GetBytes(Convert.ToInt32(hexText.Substring(i, 2), 16))[0];
    fileStream.WriteByte(bin);
}
fileStream.Close();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文