将二进制长字符串转换为十六进制 C#
我正在寻找一种将长二进制字符串转换为十六进制字符串的方法。
二进制字符串看起来像“ 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
我刚刚敲了这个。也许您可以作为起点......
I just knocked this up. Maybe you can use as a starting point...
这可能对您有帮助:
This might help you:
对于比这长的字符串,您可以简单地将其分成多个字节:
For string longer than this, you can simply break it into multiple bytes:
我想出了这个方法。我是编程和 C# 新手,但我希望你会欣赏它:
I came up with this method. I am new to programming and C# but I hope you will appreciate it:
考虑到四个位可以用一个十六进制值表示,您可以简单地以四个为一组并分别进行转换,该值不会那样改变。
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.
考虑到四个位可以用一个十六进制值表示,您可以简单地以四个为一组并分别进行转换,该值不会那样改变。
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.
如果要迭代字符串中每个字节的十六进制表示形式,可以使用以下扩展。我将米奇的答案与这个结合起来。
示例:
打印
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.
Example:
Prints
如果您使用 .NET 4.0 或更高版本,并且愿意使用 System.Numerics.dll(对于 BigInteger 类),则以下解决方案可以正常工作:
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:
使用 LINQ
Using LINQ
您可以一次输入四位数字。将此数字转换为 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.