C#如何将大HEX字符串转换为二进制 [英] C# how convert large HEX string to binary

查看:1136
本文介绍了C#如何将大HEX字符串转换为二进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个14个字符的字符串。这是一个7字节的十六进制声明。我想将它转换为二进制。我尝试使用 Convert.ToString(Convert.ToInt32(hexstring,16),2); 对于小字符串这可以工作,但对于14个字符它不会工作,因为结果太大。
我如何管理这个?请记住,转换的输出应该是一个具有56个字符的二进制字符串(我们必须保持前导零)。 (例如(字节)0x01的转换应该产生00000001而不是1)您可以将每个十六进制数字转换为四位二进制数字:

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

);

您需要一个使用System.Linq; 这是工作的文件的顶部。


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")

解决方案

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.

这篇关于C#如何将大HEX字符串转换为二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆