I am testing an example snippet that I found as an answer on another Question
However the compiler is spitting out this "Operator && cannot be applied to operands of type long and bool".
Why does it do this? As I read the code, it says "If mask and permission are greater than 0 return success bool"
Am I reading this wrong?
(Also, no one called it out as a bad example so I expected it to work. Not that I am a copy-paste coder)
bool CheckMask( long Mask, long TestPermission ) {
return Mask && TestPermission > 0;
}
long mask = 4611686844973976575;
const long MASK_ViewListItems = 0x0000000000000001;
bool HasPermission_ViewListItems = CheckMask(mask, MASK_ViewListItems);
// HasPermission_ViewListItems is true
const long MASK_UseClientIntegration = 0x0000001000000000;
bool HasPermission_UseClientIntegration = CheckMask(mask, MASK_UseClientIntegration);
// HasPermission_UseClientIntegration is false
There are an awful lot of similar questions on StackOverflow and I've clicked through most of them, there's a big list to my right as I type. None have applied to my situation, at least I was able to see the relation between the answers and my problem.
You're using && (conditional AND, only valid for bool operands) instead of & (bitwise AND, valid for bool operands or integer operands) - I suspect you want the latter, and you should also use brackets due to precedence rules. I'd change the parameter names to follow .NET naming conventions, too - and make it static as it doesn't rely on any state:
static bool CheckMask(long mask, long testPermission)
{
return (mask & testPermission) > 0;
}
You might also want to change to using an enum instead of long:
[Flags]
public enum Permissions
{
ViewListItems = 1 << 0,
...
UseClientIntegration = 1 << 9
}
static bool CheckMask(Permissions mask, Permissions testPermission)
{
return (mask & testPermission) != 0;
}
I'm guessing this is what you want:
(Mask & TestPermission) != 0
So, you need:
a bitwise & (instead of && that applies only to bool)
and I'm guessing you want to check if any bit is set including the sign bit (so != instead of >).
Related
I needed to implement a recursive method that checks whether an input is a palindrome or not. I was able to do this in one line and it works, but I'm not sure about how readable this is. I also keep getting a message "Simplify conditional ternary expression" but I'm not sure how
this is my code:
private static bool checkIfPalindrome(string i_InputToCheck, int i_StartIndex, int i_EndIndex)
{
return (i_StartIndex >= i_EndIndex) ? true : checkIfPalindrome(i_InputToCheck, i_StartIndex + 1, i_EndIndex - 1) && (i_InputToCheck[i_StartIndex] == i_InputToCheck[i_EndIndex]);
}
how readable this is
First off, naming convention: Get rid of unnecessary/uninformative parts of identifiers. For example, parameters do not need to start with i_ (presumably to denote “input”?). There’s no information conveyed here, and it adds noise. This has a huge impact on readability.
The logic itself can also be decluttered. The warning you’re getting gives you a hint that the condition can be simplified — this is always the case when your conditionals contain boolean literals.
More than anything, however, readability would benefit from breaking the expression up over multiple lines.
I would also swap the two secondary conditions, so that you first test the current characters, and then recurse further (only if the two currently tested characters are equal!):
private static bool IsPalindrome(string input, int start, int end) {
return (start >= end) ||
input[start] == input[end] &&
IsPalindrome(input, start + 1, end - 1);
}
This code relies on the correct precedence of && over ||. Some peope prefer making this operator precedence explicit by using more parentheses:
private static bool IsPalindrome(string input, int start, int end) {
return (start >= end) ||
(
input[start] == input[end] &&
IsPalindrome(input, start + 1, end - 1)
);
}
return i_StartIndex >= i_EndIndex || checkIfPalindrome(i_InputToCheck, i_StartIndex + 1, i_EndIndex - 1) && i_InputToCheck[i_StartIndex] == i_InputToCheck[i_EndIndex];
The simplification being prompted is because you're testing a boolean expression and then unnecessarily checking and returning it...
if (expression == true) is equivalent to if (expression) and
return expression ? true : false to return expression.
It is certainly not easy on the eye but I assume this is for a school exercise?
I have 3 booleans on my code (C#) and an int32 property that depends on what booleans are true and false.
Whats the best way to accomplish this in another way than if statements like:
if(a && b && !c)
d = 1;
if(a && !b && !c)
d = 2;
//etc.. ect...
EDIT: The 3 booleans must have every combination possible to set the int32 value.
EDIT 2: The value of "d" can be the same for two different boolean comparations.
It is better to capture the intent of the operation instead of explicitly check the boolean values.
For example:
public void Check()
{
if (HasOrdered())
{
// do logic
}
}
private bool HasOrdered()
{
return a && !b && !c;
}
private bool HasBooked()
{
return a && b && !c;
}
You could use a Karnaugh map to reduce your equations and have fewer ifs.
https://en.wikipedia.org/wiki/Karnaugh_map
I think what your doing now is perfectly fine and any other solutions would be down to preference.
My preference, where it applies would be to separate the checks out if possible.
if (!a)
return;
if (!b)
return;
if (!c)
return;
This would be useful in the event that you need to check certain prereqs before issuing a function, like if the user has logged in, if a parameter exists and is in the right context, along with other items.
Like i said this might not apply but i just wanted to voice my opinion
You could do the lookup table hint given by #Adriano, assuming you have lookup_table filled with values for index [0..8):
var index = new [] { a,b,c }.Aggregate(0, (a,i) => return 2*a + (i?1:0));
int d = lookup_table[index];
Edit The EDIT of the question made this irrelevant: What does d mean?
If it's the count of false values (possible from the sample code), make it
int d = new [] { a,b,c }.Count(b => !b);
I don't see anything wrong with how you're doing it, but if the output is the same for multiple conditions you may be able to simplify if by creating a truth table and simplifying the conditions.
For example, if d should be 0 anytime a is false you could simplify to:
if(a)
if(b && !c)
d = 1;
if(!b && !c)
d = 2;
...
else
d = 0;
Or if there is some mathematical pattern (e.g. a, b, and c represent the three digits of a binary number) then you could do bit arithmetic.
If, however, you have 8 distinct outcomes (one for each combination of a, b, and c) then your method is fine.
I just want to know if exactly one enum flag is set, not which ones. My current thinking is to check if it is a power of 2. Is there a better way built into enum types?
[Flags]
enum Foo
{
Flag1 = 0x01,
Flag2 = 0x02,
Flag3 = 0x04,
Flag4 = 0x08,
Flag5 = 0x10,
Flag6 = 0x20,
Flag7 = 0x40,
Flag8 = 0x80
}
private bool ExactlynOneFlagSet(Foo myFoo)
{
var x = (byte) myFoo;
return (x != 0) && ((x & (x - 1)) == 0); //Check if a power of 2
}
if(!ExactlynOneFlagSet(Foo myFoo))
{
//Do something
}
Its a Bit operation!
if ((myFoo & (myFoo -1)) != 0) //has more than 1 flag
The statement checks if the value of myFoo is not power of two. Or, vice versa, the statement (myFoo & (myFoo -1)) == 0 checks for power of two. The idea is that only single flag values will be power of two. Setting more than one flag will result in a non power of two value of myFoo.
More information can be found in this answer to a similar question: https://stackoverflow.com/a/1662162/2404788.
For more information about bit operations go to http://en.wikipedia.org/wiki/Bitwise_operation
If the enum doesn't define explicit combinations of flags, you can just check if the value is defined in the enum:
private bool ExactlynOneFlagSet(Foo myFoo)
{
return Enum.IsDefined(typeof(Foo), myFoo);
}
private bool ExatlyOneFlagSet(Foo myFoo)
{
return !myFoo.ToString().Contains(',');
}
If you're using .NET Core 3.0+, you can use PopCount, it returns the number of "1" bits in a uint or ulong and uses the POPCNT CPU instruction (if CPU supports SSE4, otherwise it'll use a software fallback).
public static bool ExactlyOneFlagSet(Foo foo)
{
return BitOperations.PopCount((ulong)foo) == 1;
}
Foo one = Foo.Flag1;
Foo two = Foo.Flag1 | Foo.Flag2;
Console.WriteLine(ExactlyOneFlagSet(one)); //true
Console.WriteLine(ExactlyOneFlagSet(two)); //false
As Jacob explained in a comment your method is not correct at all. Personally I always avoid programming mathematically, especially when it comes to logic. So my solution would be something like "if I wanted to know the count is one, so count it and compare it to number one".
Here it is:
public static bool OneIsSet(Type enumType, byte value)
{
return Enum.GetValues(enumType).Cast<byte>().Count(v => (value & v) == v) == 1;
}
public static bool OneIsSet(Type enumType, int value)
{
return Enum.GetValues(enumType).Cast<byte>().Count(v => (value & v) == v) == 1;
}
And you can use it for your foo type like this:
var toReturnFalse = (byte)(foo.Flag1 | foo.Flag2);
var toReturnTrue = (byte)foo.Flag1;
var trueWillBeReturned = OneIsSet(typeof(foo), toReturnTrue);
var falseWillBeReturned = OneIsSet(typeof(foo), toReturnFalse);
I believe this methods could be written in a more generic way using Generics and type handling methods. However I included the methods for most common base types for enums which are int and byte. But you could also write the same for short and other types.
Also you may just inline the code in your code. It is only one line of code.
Also using this method you could see if the number of set flags is two or more. The below code returns true if the count of set flags is equal to 'n'.
Enum.GetValues(enumType).Cast<byte>().Count(v => (value & v) == v) == n;
I have the following enum:
[Flags]
public enum Permissions
{
None = 0x0000,
All = 0xFFFF
}
If either None or All are raised, no other flag should be raised.
How do I check if either None or All are raised and nothing else?
In a flags enum, None should be zero, and All should be the cumulative bitwise sum. This makes the maths pretty easy, then:
if(value == Permissions.None || value == Permissions.All) {...}
maybe written as a switch if you prefer...
However, in the general case, you can test for a complete flags match (against any number of bits) with:
if((value & wanted) == wanted) {...}
and to test for any overlap (i.e. any common bits - wanted needs to be non-zero):
if((value & wanted) != 0) {...}
if(value|Permissions.None)==Permissions.None;
This can check Permissions.None is raised. The rest can be done in the same manner.
Let's say I have the following
int susan = 2; //0010
int bob = 4; //0100
int karen = 8; //1000
and I pass 10 (8 + 2) as a parameter to a method and I want to decode this to mean susan and karen
I know that 10 is 1010
but how can I do some logic to see if a specific bit is checked as in
if (condition_for_karen) // How to quickly check whether effective karen bit is 1
Right now all i can think of is to check whether the number i passed is
14 // 1110
12 // 1100
10 // 1010
8 // 1000
When I have a larger number of actual bits in my real world scenario, this seems impractical, what is a better way using a mask to just check whether or not I meet the condition for just karen?
I can think of shifting left then back then shifting right then back to clear bits other than the one I'm interested in, but this also seems overly complex.
The traditional way to do this is to use the Flags attribute on an enum:
[Flags]
public enum Names
{
None = 0,
Susan = 1,
Bob = 2,
Karen = 4
}
Then you'd check for a particular name as follows:
Names names = Names.Susan | Names.Bob;
// evaluates to true
bool susanIsIncluded = (names & Names.Susan) != Names.None;
// evaluates to false
bool karenIsIncluded = (names & Names.Karen) != Names.None;
Logical bitwise combinations can be tough to remember, so I make life easier on myself with a FlagsHelper class*:
// The casts to object in the below code are an unfortunate necessity due to
// C#'s restriction against a where T : Enum constraint. (There are ways around
// this, but they're outside the scope of this simple illustration.)
public static class FlagsHelper
{
public static bool IsSet<T>(T flags, T flag) where T : struct
{
int flagsValue = (int)(object)flags;
int flagValue = (int)(object)flag;
return (flagsValue & flagValue) != 0;
}
public static void Set<T>(ref T flags, T flag) where T : struct
{
int flagsValue = (int)(object)flags;
int flagValue = (int)(object)flag;
flags = (T)(object)(flagsValue | flagValue);
}
public static void Unset<T>(ref T flags, T flag) where T : struct
{
int flagsValue = (int)(object)flags;
int flagValue = (int)(object)flag;
flags = (T)(object)(flagsValue & (~flagValue));
}
}
This would allow me to rewrite the above code as:
Names names = Names.Susan | Names.Bob;
bool susanIsIncluded = FlagsHelper.IsSet(names, Names.Susan);
bool karenIsIncluded = FlagsHelper.IsSet(names, Names.Karen);
Note I could also add Karen to the set by doing this:
FlagsHelper.Set(ref names, Names.Karen);
And I could remove Susan in a similar way:
FlagsHelper.Unset(ref names, Names.Susan);
*As Porges pointed out, an equivalent of the IsSet method above already exists in .NET 4.0: Enum.HasFlag. The Set and Unset methods don't appear to have equivalents, though; so I'd still say this class has some merit.
Note: Using enums is just the conventional way of tackling this problem. You can totally translate all of the above code to use ints instead and it'll work just as well.
Easy Way:
[Flags]
public enum MyFlags {
None = 0,
Susan = 1,
Alice = 2,
Bob = 4,
Eve = 8
}
To set the flags use logical "or" operator |:
MyFlags f = new MyFlags();
f = MyFlags.Alice | MyFlags.Bob;
And to check if a flag is included use HasFlag:
if(f.HasFlag(MyFlags.Alice)) { /* true */}
if(f.HasFlag(MyFlags.Eve)) { /* false */}
if ( ( param & karen ) == karen )
{
// Do stuff
}
The bitwise 'and' will mask out everything except the bit that "represents" Karen. As long as each person is represented by a single bit position, you could check multiple people with a simple:
if ( ( param & karen ) == karen )
{
// Do Karen's stuff
}
if ( ( param & bob ) == bob )
// Do Bob's stuff
}
I have included an example here which demonstrates how you might store the mask in a database column as an int, and how you would reinstate the mask later on:
public enum DaysBitMask { Mon=0, Tues=1, Wed=2, Thu = 4, Fri = 8, Sat = 16, Sun = 32 }
DaysBitMask mask = DaysBitMask.Sat | DaysBitMask.Thu;
bool test;
if ((mask & DaysBitMask.Sat) == DaysBitMask.Sat)
test = true;
if ((mask & DaysBitMask.Thu) == DaysBitMask.Thu)
test = true;
if ((mask & DaysBitMask.Wed) != DaysBitMask.Wed)
test = true;
// Store the value
int storedVal = (int)mask;
// Reinstate the mask and re-test
DaysBitMask reHydratedMask = (DaysBitMask)storedVal;
if ((reHydratedMask & DaysBitMask.Sat) == DaysBitMask.Sat)
test = true;
if ((reHydratedMask & DaysBitMask.Thu) == DaysBitMask.Thu)
test = true;
if ((reHydratedMask & DaysBitMask.Wed) != DaysBitMask.Wed)
test = true;
To combine bitmasks you want to use bitwise-or. In the trivial case where every value you combine has exactly 1 bit on (like your example), it's equivalent to adding them. If you have overlapping bits however, or'ing them handles the case gracefully.
To decode the bitmasks you and your value with a mask, like so:
if(val & (1<<1)) SusanIsOn();
if(val & (1<<2)) BobIsOn();
if(val & (1<<3)) KarenIsOn();
One other really good reason to use a bitmask vs individual bools is as a web developer, when integrating one website to another, we frequently need to send parameters or flags in the querystring. As long as all of your flags are binary, it makes it much simpler to use a single value as a bitmask than send multiple values as bools. I know there are otherways to send data (GET, POST, etc.), but a simple parameter on the querystring is most of the time sufficient for nonsensitive items. Try to send 128 bool values on a querystring to communicate with an external site. This also gives the added ability of not pushing the limit on url querystrings in browsers