将二进制长字符串转换为十六进制 C#

发布于 2024-10-31 20:25:07 字数 348 浏览 1 评论 0原文

我正在寻找一种将长二进制字符串转换为十六进制字符串的方法。

二进制字符串看起来像“ 0110011011111110011110101111111111111111111101101101110111001110101101101101101111”“

我已经尝试过,

hex = String.Format("{0:X2}", Convert.ToUInt64(hex, 2));

但是只有在二进制字符串拟合到UINT64中的uint64时,这只有足够长的时间。

还有另一种方法可以将二进制字符串转换为十六进制吗?

谢谢

I'm looking for a way to convert a long string of binary to a hex string.

the binary string looks something like this "0110011010010111001001110101011100110100001101101000011001010110001101101011"

I've tried using

hex = String.Format("{0:X2}", Convert.ToUInt64(hex, 2));

but that only works if the binary string fits into a Uint64 which if the string is long enough it won't.

is there another way to convert a string of binary into hex?

Thanks

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

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

发布评论

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

评论(11

放赐 2024-11-07 20:25:07

我刚刚敲了这个。也许您可以作为起点......

public static string BinaryStringToHexString(string binary)
{
    if (string.IsNullOrEmpty(binary))
        return binary;

    StringBuilder result = new StringBuilder(binary.Length / 8 + 1);

    // TODO: check all 1's or 0's... throw otherwise

    int mod4Len = binary.Length % 8;
    if (mod4Len != 0)
    {
        // pad to length multiple of 8
        binary = binary.PadLeft(((binary.Length / 8) + 1) * 8, '0');
    }

    for (int i = 0; i < binary.Length; i += 8)
    {
        string eightBits = binary.Substring(i, 8);
        result.AppendFormat("{0:X2}", Convert.ToByte(eightBits, 2));
    }

    return result.ToString();
}

I just knocked this up. Maybe you can use as a starting point...

public static string BinaryStringToHexString(string binary)
{
    if (string.IsNullOrEmpty(binary))
        return binary;

    StringBuilder result = new StringBuilder(binary.Length / 8 + 1);

    // TODO: check all 1's or 0's... throw otherwise

    int mod4Len = binary.Length % 8;
    if (mod4Len != 0)
    {
        // pad to length multiple of 8
        binary = binary.PadLeft(((binary.Length / 8) + 1) * 8, '0');
    }

    for (int i = 0; i < binary.Length; i += 8)
    {
        string eightBits = binary.Substring(i, 8);
        result.AppendFormat("{0:X2}", Convert.ToByte(eightBits, 2));
    }

    return result.ToString();
}
从此见与不见 2024-11-07 20:25:07

这可能对您有帮助:

string HexConverted(string strBinary)
    {
        string strHex = Convert.ToInt32(strBinary,2).ToString("X");
        return strHex;
    }

This might help you:

string HexConverted(string strBinary)
    {
        string strHex = Convert.ToInt32(strBinary,2).ToString("X");
        return strHex;
    }
捶死心动 2024-11-07 20:25:07
Convert.ToInt32("1011", 2).ToString("X");

对于比这长的字符串,您可以简单地将其分成多个字节:

var binary = "0110011010010111001001110101011100110100001101101000011001010110001101101011";
var hex = string.Join(" ", 
            Enumerable.Range(0, binary.Length / 8)
            .Select(i => Convert.ToByte(binary.Substring(i * 8, 8), 2).ToString("X2")));
Convert.ToInt32("1011", 2).ToString("X");

For string longer than this, you can simply break it into multiple bytes:

var binary = "0110011010010111001001110101011100110100001101101000011001010110001101101011";
var hex = string.Join(" ", 
            Enumerable.Range(0, binary.Length / 8)
            .Select(i => Convert.ToByte(binary.Substring(i * 8, 8), 2).ToString("X2")));
_蜘蛛 2024-11-07 20:25:07

我想出了这个方法。我是编程和 C# 新手,但我希望你会欣赏它:

static string BinToHex(string bin)
{
    StringBuilder binary = new StringBuilder(bin);
    bool isNegative = false;
    if (binary[0] == '-')
    {
        isNegative = true;
        binary.Remove(0, 1);
    }

    for (int i = 0, length = binary.Length; i < (4 - length % 4) % 4; i++) //padding leading zeros
    {
        binary.Insert(0, '0');
    }

    StringBuilder hexadecimal = new StringBuilder();
    StringBuilder word = new StringBuilder("0000");
    for (int i = 0; i < binary.Length; i += 4)
    {
        for (int j = i; j < i + 4; j++)
        {
            word[j % 4] = binary[j];
        }

        switch (word.ToString())
        {
            case "0000": hexadecimal.Append('0'); break;
            case "0001": hexadecimal.Append('1'); break;
            case "0010": hexadecimal.Append('2'); break;
            case "0011": hexadecimal.Append('3'); break;
            case "0100": hexadecimal.Append('4'); break;
            case "0101": hexadecimal.Append('5'); break;
            case "0110": hexadecimal.Append('6'); break;
            case "0111": hexadecimal.Append('7'); break;
            case "1000": hexadecimal.Append('8'); break;
            case "1001": hexadecimal.Append('9'); break;
            case "1010": hexadecimal.Append('A'); break;
            case "1011": hexadecimal.Append('B'); break;
            case "1100": hexadecimal.Append('C'); break;
            case "1101": hexadecimal.Append('D'); break;
            case "1110": hexadecimal.Append('E'); break;
            case "1111": hexadecimal.Append('F'); break;
            default:
                return "Invalid number";
        }
    }

    if (isNegative)
    {
        hexadecimal.Insert(0, '-');
    }

    return hexadecimal.ToString();
}

I came up with this method. I am new to programming and C# but I hope you will appreciate it:

static string BinToHex(string bin)
{
    StringBuilder binary = new StringBuilder(bin);
    bool isNegative = false;
    if (binary[0] == '-')
    {
        isNegative = true;
        binary.Remove(0, 1);
    }

    for (int i = 0, length = binary.Length; i < (4 - length % 4) % 4; i++) //padding leading zeros
    {
        binary.Insert(0, '0');
    }

    StringBuilder hexadecimal = new StringBuilder();
    StringBuilder word = new StringBuilder("0000");
    for (int i = 0; i < binary.Length; i += 4)
    {
        for (int j = i; j < i + 4; j++)
        {
            word[j % 4] = binary[j];
        }

        switch (word.ToString())
        {
            case "0000": hexadecimal.Append('0'); break;
            case "0001": hexadecimal.Append('1'); break;
            case "0010": hexadecimal.Append('2'); break;
            case "0011": hexadecimal.Append('3'); break;
            case "0100": hexadecimal.Append('4'); break;
            case "0101": hexadecimal.Append('5'); break;
            case "0110": hexadecimal.Append('6'); break;
            case "0111": hexadecimal.Append('7'); break;
            case "1000": hexadecimal.Append('8'); break;
            case "1001": hexadecimal.Append('9'); break;
            case "1010": hexadecimal.Append('A'); break;
            case "1011": hexadecimal.Append('B'); break;
            case "1100": hexadecimal.Append('C'); break;
            case "1101": hexadecimal.Append('D'); break;
            case "1110": hexadecimal.Append('E'); break;
            case "1111": hexadecimal.Append('F'); break;
            default:
                return "Invalid number";
        }
    }

    if (isNegative)
    {
        hexadecimal.Insert(0, '-');
    }

    return hexadecimal.ToString();
}
白色秋天 2024-11-07 20:25:07

考虑到四个位可以用一个十六进制值表示,您可以简单地以四个为一组并分别进行转换,该值不会那样改变。

string bin = "11110110";

int rest = bin.Length % 4;
bin = bin.PadLeft(rest, '0'); //pad the length out to by divideable by 4

string output = "";

for(int i = 0; i <= bin.Length - 4; i +=4)
{
    output += string.Format("{0:X}", Convert.ToByte(bin.Substring(i, 4), 2));
}

Considering four bits can be expressed by one hex value, you can simply go by groups of four and convert them seperately, the value won't change that way.

string bin = "11110110";

int rest = bin.Length % 4;
bin = bin.PadLeft(rest, '0'); //pad the length out to by divideable by 4

string output = "";

for(int i = 0; i <= bin.Length - 4; i +=4)
{
    output += string.Format("{0:X}", Convert.ToByte(bin.Substring(i, 4), 2));
}
青丝拂面 2024-11-07 20:25:07

考虑到四个位可以用一个十六进制值表示,您可以简单地以四个为一组并分别进行转换,该值不会那样改变。

string bin = "11110110";

int rest = bin.Length % 4;
if(rest != 0)
    bin = new string('0', 4-rest) + bin; //pad the length out to by divideable by 4

string output = "";

for(int i = 0; i <= bin.Length - 4; i +=4)
{
    output += string.Format("{0:X}", Convert.ToByte(bin.Substring(i, 4), 2));
}

Considering four bits can be expressed by one hex value, you can simply go by groups of four and convert them seperately, the value won't change that way.

string bin = "11110110";

int rest = bin.Length % 4;
if(rest != 0)
    bin = new string('0', 4-rest) + bin; //pad the length out to by divideable by 4

string output = "";

for(int i = 0; i <= bin.Length - 4; i +=4)
{
    output += string.Format("{0:X}", Convert.ToByte(bin.Substring(i, 4), 2));
}
只是一片海 2024-11-07 20:25:07

如果要迭代字符串中每个字节的十六进制表示形式,可以使用以下扩展。我将米奇的答案与这个结合起来。

static class StringExtensions
{
    public static IEnumerable<string> ToHex(this String s) {
        if (s == null)
            throw new ArgumentNullException("s");

        int mod4Len = s.Length % 8;
        if (mod4Len != 0)
        {
            // pad to length multiple of 8
            s = s.PadLeft(((s.Length / 8) + 1) * 8, '0');
        }

        int numBitsInByte = 8;
        for (var i = 0; i < s.Length; i += numBitsInByte)
        {
            string eightBits = s.Substring(i, numBitsInByte);
            yield return string.Format("{0:X2}", Convert.ToByte(eightBits, 2));
        }
    }
}

示例:

string test = "0110011010010111001001110101011100110100001101101000011001010110001101101011";

foreach (var hexVal in test.ToHex())
{
    Console.WriteLine(hexVal);  
}

打印

06
69
72
75
73
43
68
65
63
6B

If you want to iterate over the hexadecimal representation of each byte in the string, you could use the following extension. I've combined Mitch's answer with this.

static class StringExtensions
{
    public static IEnumerable<string> ToHex(this String s) {
        if (s == null)
            throw new ArgumentNullException("s");

        int mod4Len = s.Length % 8;
        if (mod4Len != 0)
        {
            // pad to length multiple of 8
            s = s.PadLeft(((s.Length / 8) + 1) * 8, '0');
        }

        int numBitsInByte = 8;
        for (var i = 0; i < s.Length; i += numBitsInByte)
        {
            string eightBits = s.Substring(i, numBitsInByte);
            yield return string.Format("{0:X2}", Convert.ToByte(eightBits, 2));
        }
    }
}

Example:

string test = "0110011010010111001001110101011100110100001101101000011001010110001101101011";

foreach (var hexVal in test.ToHex())
{
    Console.WriteLine(hexVal);  
}

Prints

06
69
72
75
73
43
68
65
63
6B
孤独患者 2024-11-07 20:25:07

如果您使用 .NET 4.0 或更高版本,并且愿意使用 System.Numerics.dll(对于 BigInteger 类),则以下解决方案可以正常工作:

public static string ConvertBigBinaryToHex(string bigBinary)
{
    BigInteger bigInt = BigInteger.Zero;
    int exponent = 0;

    for (int i = bigBinary.Length - 1; i >= 0; i--, exponent++)
    {
        if (bigBinary[i] == '1')
            bigInt += BigInteger.Pow(2, exponent);
    }

    return bigInt.ToString("X");
}

If you're using .NET 4.0 or later and if you're willing to use System.Numerics.dll (for BigInteger class), the following solution works fine:

public static string ConvertBigBinaryToHex(string bigBinary)
{
    BigInteger bigInt = BigInteger.Zero;
    int exponent = 0;

    for (int i = bigBinary.Length - 1; i >= 0; i--, exponent++)
    {
        if (bigBinary[i] == '1')
            bigInt += BigInteger.Pow(2, exponent);
    }

    return bigInt.ToString("X");
}
倾`听者〃 2024-11-07 20:25:07
static string BinToHex(string bin)
{
    if (bin == null)
        throw new ArgumentNullException("bin");
    if (bin.Length % 8 != 0)
        throw new ArgumentException("The length must be a multiple of 8", "bin");

    var hex = Enumerable.Range(0, bin.Length / 8)
                     .Select(i => bin.Substring(8 * i, 8))
                     .Select(s => Convert.ToByte(s, 2))
                     .Select(b => b.ToString("x2"));
    return String.Join(null, hex);
}
static string BinToHex(string bin)
{
    if (bin == null)
        throw new ArgumentNullException("bin");
    if (bin.Length % 8 != 0)
        throw new ArgumentException("The length must be a multiple of 8", "bin");

    var hex = Enumerable.Range(0, bin.Length / 8)
                     .Select(i => bin.Substring(8 * i, 8))
                     .Select(s => Convert.ToByte(s, 2))
                     .Select(b => b.ToString("x2"));
    return String.Join(null, hex);
}
你怎么这么可爱啊 2024-11-07 20:25:07

使用 LINQ

   string BinaryToHex(string binaryString)
            {
                var offset = 0;
                StringBuilder sb = new();
                
                while (offset < binaryString.Length)
                {
                    var nibble = binaryString
                        .Skip(offset)
                        .Take(4);

                    sb.Append($"{Convert.ToUInt32(nibble.toString()), 2):X}");
                    offset += 4;
                }

                return sb.ToString();

            }

Using LINQ

   string BinaryToHex(string binaryString)
            {
                var offset = 0;
                StringBuilder sb = new();
                
                while (offset < binaryString.Length)
                {
                    var nibble = binaryString
                        .Skip(offset)
                        .Take(4);

                    sb.Append(
quot;{Convert.ToUInt32(nibble.toString()), 2):X}");
                    offset += 4;
                }

                return sb.ToString();

            }
傻比既视感 2024-11-07 20:25:07

您可以一次输入四位数字。将此数字转换为 ex (就像您所做的那样)然后将字符串连接在一起。因此,您将获得一个表示十六进制数字的字符串,与大小无关。根据输入字符串中 MSB 的起始位置,您按照我所描述的方式获得的输出字符串可能必须反转

You can take the input number four digit at a time. Convert this digit to ex ( as you did is ok ) then concat the string all together. So you obtain a string representing the number in hex, independetly from the size. Depending on where start MSB on your input string, may be the output string you obtain the way i described must be reversed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文