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

本文关键字:字符串 转换 二进制 十六进制 | 更新日期: 2023-09-27 18:01:34

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

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

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

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

你需要一个using System.Linq;在文件的顶部为这个工作

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

也许吗?或者

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

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

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"

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

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

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

你可以这样做。

我把它放在一个类称为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);

转换。fromxstring已经在。net 5中引入了

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

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

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

Int64代替Int32怎么样?

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

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

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