Method equivalent to Biginteger.and() in C#

Asked

Viewed 93 times

9

I need to convert the java code below to C#:

public static boolean verificaPermissao(BigInteger perm1, BigInteger perm) {

    if (perm1 == null || perm == null || (perm1.equals(BigInteger.ZERO) || (perm.equals(BigInteger.ZERO))))
        return false;

    return !perm.and(perm1).equals(BigInteger.ZERO);
}

But I don’t know what the C# function for and

public static bool verificaPermissao(BigInteger perm1, BigInteger perm)
{
    if (perm1 == null || perm == null || (perm1.IsZero) || (perm.IsZero ))
        return false;

    //Converter para C#
    //return !perm.and(perm1).equals(BigInteger.ZERO);Converter para C#
}

The method and does not exist in the BigInteger of the C#.

2 answers

9


The and is the same thing as using the operator & (bitwise and) between the two values and this is equal in the two languages.

I made other adaptations too. In C#, BigInteger is a guy by worth, meaning he’ll never be null and the zero check is already done in the return.

public static bool VerificaPermissao(BigInteger perm1, BigInteger perm) 
{        
    return (perm & perm1) != 0;
}
  • Perfect! I thought java and did more commands than & c#. Thank you very much!

  • Operator "!" cannot be Applied to operand of type 'Biginteger'

  • Now yes, thank you!

8

If you want the bitwise has the operator. If you want the boolean, he doesn’t have to have it anyway since the operation is independent of being int, BigInteger or something else.

using static System.Console;
using System.Numerics;

public class Program {
    public static void Main() {
        WriteLine(VerificaPermissao((BigInteger)1, (BigInteger)0));
        WriteLine(VerificaPermissao((BigInteger)1, (BigInteger)1));
        WriteLine(VerificaPermissao((BigInteger)2, (BigInteger)1));
    }
    public static bool VerificaPermissao(BigInteger perm1, BigInteger perm) => (perm & perm1) != 0;
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

I took advantage and simplified since BigInteger in C# is a type by value and has operators for all basic mathematical operations. This code is more idiomatic in C#.

Whomever compare that the result is the same in Java.

  • that I wanted the bitwise!

  • @Bertuzzi edited the question by simplifying the code, in C# it is easier than Java. And it gets faster.

Browser other questions tagged

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