Click here to Skip to main content
15,896,489 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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.
C#
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.
Posted
Updated 25-Apr-18 5:39am
v2
Comments
Patrice T 25-Apr-18 16:39pm    
Can you show sample input and output ?

To convert any array of bytes a hex string you just need:
C#
StringBuilder hexString = new StringBuilder();
for (int i = 0; i < byteArray.Length; ++i)
{
    hexString.Append(string.Format("{0:X2}", byteArray[i]));
}
 
Share this answer
 
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.
 
Share this answer
 
Comments
Prat142 25-Apr-18 10:48am    
Yes line.length = 128 ..it will be always in multiple of 8

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900