Converting Java code to C#

Asked

Viewed 478 times

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 through Google also could not do.

The real question is the lines

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

I look forward to some help. To tell you the truth I’ve given up hope of making it work in C#, I hope you get it with your help :)

Thanks in advance.

1 answer

5


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

Note also that the code writing convention C# 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# code 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 most modern versions of C# (6+) it is possible to write in the form of Expression body and use interpolation of string.

public static long convertStringToBitboard(string binary) => 
    binary[0] == '0' ? Convert.ToInt64(binary, 2) : Convert.ToInt64($"1{binary.Substring(2)}", 2) * 2;
  • I can at least know why I voted against?

  • Thank you very much LINQ. I am new here. I am marking the question as solved. Well... it was not I who negative. Again thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.