二进制到十六进制转换 [英] Binary to hexadecimel conversion

查看:88
本文介绍了二进制到十六进制转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码::我已经获得了已经处理的数组和格式异常的Argument Out of Range异常::如何改进代码以消除这些异常?



我的输入字符串是128位二进制字符串,我需要将其转换为16字节的十六进制值。

I have following code:: I am getting the Argument Out of Range exception for the array and format exception that I already handled::How the code can be improved to eliminate these exceptions?

My input string is 128 bit binary string which I need to convert into 16 byte Hexadecimal value.

var numOfBytes = (int)Math.Ceiling(line.Length / 8m);
                    var linebytes = new byte[numOfBytes];
                    var lenth = 8;

                    for (int j = 1; j <= numOfBytes; j++)
                    {
                        var startIndex = line.Length - 8 * j;
                        if (!int.TryParse(line, out lenth))
                        {
                            Console.WriteLine("{0} is non parsable character at the end of the string", line);
                        }
                        if (startIndex < 0)
                        {
                            lenth = 8 + startIndex;
                            startIndex = 0;
                        }
                        

                        string sub = line.Substring(startIndex, lenth);
                        linebytes[numOfBytes - j] = Convert.ToByte(sub, 2);





我尝试了什么:



我试过的代码在说明中。



What I have tried:

The code I have tried is in the description.

推荐答案

什么是line.Length?它是8的倍数?



numOfBytes从line.Length / 8向上舍入,这意味着numOfBytes * 8可能大于line.Length。

在循环结束时,startIndex = line.Length - 8 * numOfBytes,可能小于0.

line.SubString(startIndex,length)将抛出ArgumentOutOfRange例外。
What is line.Length? Is it a multiple of 8?

numOfBytes is rounded up up from line.Length/8, which means numOfBytes * 8 may be larger than line.Length.
At the end of your loop, startIndex = line.Length - 8 * numOfBytes, which may be less than 0.
line.SubString(startIndex, length) will throw an ArgumentOutOfRange exception here.


要转换任何字节数组,只需要一个十六进制字符串:

To convert any array of bytes a hex string you just need:
StringBuilder hexString = new StringBuilder();
for (int i = 0; i < byteArray.Length; ++i)
{
    hexString.Append(string.Format("{0:X2}", byteArray[i]));
}


这篇关于二进制到十六进制转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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