Conversion of Java code to C #

3

I would like a help to convert the following code in Java to C #.

public static long convertStringToBitboard(String Binary) 
{
    if (Binary.charAt(0)=='0') 
    {
        return Long.parseLong(Binary, 2);
    } else 
    {
        return Long.parseLong("1"+Binary.substring(2), 2)*2;
    }
}

I tried to use tools that perform machine translation, but I did not succeed. Searching for Google also failed to do.

The real question is the lines

return Long.parseLong(Binary, 2);
return Long.parseLong("1"+Binary.substring(2), 2)*2;

I'm waiting for some help. I have already given up hope of making this work in C #, I hope you can do it with your help:)

Thank you in advance.

    
asked by anonymous 19.04.2018 / 23:50

1 answer

5

The only thing that changes is that the method to convert a string to a 64-bit integer is Convert.ToInt64 instead of Long.parseLong .

Also note that the C # code writing convention says that the methods should be written in PascalCase and that the parameters should be written in camelCase (in this case it is the same as the Java convention).

Both Java and C # could be written in a shorter way.

public static long ConvertStringToBitboard(string binary) 
{
    return binary[0] == '0' ? Convert.ToInt64(binary, 2) : Convert.ToInt64("1" + binary.Substring(2), 2) * 2;
}

In the latest versions of C # (6+) it is possible to write in the form of expression body and use string interpolation.

public static long convertStringToBitboard(string binary) => 
    binary[0] == '0' ? Convert.ToInt64(binary, 2) : Convert.ToInt64($"1{binary.Substring(2)}", 2) * 2;
    
19.04.2018 / 23:56