C# 如何将大的十六进制字符串转换为二进制
我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
您只需将每个十六进制数字转换为四个二进制数字即可:
您需要在文件顶部添加
using System.Linq;
才能使其正常工作。You can just convert each hexadecimal digit into four binary digits:
You need a
using System.Linq;
a the top of the file for this to work.或许?或者
Maybe? Or
为什么不采用简单的方法并定义您自己的映射呢?
请注意,这将保留前导零。因此,
"aa"
将转换为"10101010"
,而"00000aa"
将转换为"0000000000000000000010101010"
。Why not just take the simple approach and define your own mapping?
Note that this will keep leading zeros. So
"aa"
would be converted to"10101010"
while"00000aa"
would be converted to"0000000000000000000010101010"
.您可以使用此代码从十六进制字符串获取字节数组
You can get a byte array from hex string using this code
Convert.FromHexString已在.Net 5中引入
Convert.FromHexString has been introduced in .Net 5
我的C++背景答案:
My C++ background answer:
你可以这样做。
我把它放在一个名为 UtilMath 的类中
这是一个好主意,因为如果您在不同的程序中使用它,您可以再次使用该类。
顾名思义,这适用于我所有的数学函数。
现在,在使用它之前,您需要包含它,
然后如果您需要使用它,您可以通过“
或
希望这有帮助”来调用它。
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.
now before you use it you need to include it,
then if you need to use it you can call it by going
Or
Hope this helps.
如果一次转换一个字符怎么办?我无法对此进行测试,但这个想法应该可行。
What if you convert one character at a time? I'm can't test this out, but the idea should work.
使用
Int64
而不是Int32
怎么样?How about using
Int64
instead ofInt32
?如果你需要一个字节数组,你可以通过以下方式获取:
但如果是直接保存到文件,我会直接这样做:
If you need a byte array, you can get it by:
But if it is directly to save to a file, I would do it directly: