-2

I am implementing a number conversion program from Visual Basic.Net to C #. This is the original code that converts a number from binary to hexadecimal.

Public Function BinToHex(ByVal BinStr As String) As String 
   Dim HexStr As String 
   HexStr = "" 
   Dim i As Integer 
   For i = 1 To Len(BinStr) Step 4 
       HexStr = HexStr & DecToHex(BinToDec(Mid(BinStr, i, 4))) 
   Next i 
   Return HexStr 
End Function

In C # I have the following code:

public string BinToHex(string BinStr) {
    string HexStr;
    HexStr = "";
    int i;
    var loopTo = BinStr.Length;
    for (i = 1; i <= loopTo; i +=4){
        HexStr = HexStr + DecToHex(BinToDec(BinStr.Substring((i - 1), 4)));
    }
    return HexStr;
}

This code makes use of the C#'s Substring function which, knowing that it is handled differently from Basic's mid function, we must subtract 1 from the variable that is used as the function's argument. But executing the function, for whatever value it receives, it throws the following error. The error poster is this:

Substring function error poster with invalid parameters

Alejandro Caro
  • 998
  • 1
  • 10
  • 22
  • Please do not include code or errors as images. Copy the exception text and include it as text instead. – JonasH Jul 25 '21 at 21:11
  • 1
    [_Convert.ToInt32(string, base)_](https://learn.microsoft.com/en-us/dotnet/api/system.convert.toint32?view=net-5.0#System_Convert_ToInt32_System_String_System_Int32_) ? – Steve Jul 25 '21 at 21:13
  • 1
    Are you guaranteed that the string has a length that is an even multiple of four? if not, you will get errors. – JonasH Jul 25 '21 at 21:16

1 Answers1

0

As substring docs says, you can't extend the string length, so you have to check if BinStr.Length % 4 == 0

Leszek Mazur
  • 2,443
  • 1
  • 14
  • 28