I have a short-variable in C# and want to change a specific bit. How can I do it the easiest way?
Do you mean something like this?
public static short SetBit(short input, int bit)
{
return (short) (input | (1 << bit));
}
public static short ClearBit(short input, int bit)
{
return (short) (input & ~(1 << bit));
}
You could even make them extension methods if you want to.
Take a look at bitwise operators:
short i = 4;
short k = 1;
Console.WriteLine(i | k); //should write 5
You can see a list of the operators under the Logical (boolean and bitwise) section here.
Also, did some poking around and found this bitwise helper class. Might be worth checking out depending on your needs.
Related
I have a uint called Forced that contains 32 bits.
I do stuff like:
if(Forced & 512)
doStuff();
What I am looking to do is put forced into an array which would then turn into:
if(ForcedArray[(int)Math.Log(512,2)])
doStuff();
Is there a convenient way in .NET to do this? What would be a convenient way to convert a bitfield to an array?
You could write an extension method for this:
public static class UIntExtensions
{
public static bool IsBitSet(this uint i, int bitNumber)
{
return i & (1 << bitNumber) != 0;
}
}
Or, if you want to do this the C#6 way:
public static class UIntExtensions
{
public static bool IsBitSet(this uint i, int bitNumber) => (i & (1 << bitNumber)) != 0;
}
Which is pretty easy to use from code:
if(Forced.IsBitSet((int)Math.Log(512,2)))
doStuff();
Obviously, a few checks for having a bit number >= 0 or <= 31 need to be added, but you get the idea.
Using bit-shift to access bits of an integer Forced & (1 << bitNumber) sounds like a good approach (nice function wrapping the access is shown in Ron Beyer's answer).
Most reader of the code will be puzzled by such transformation of compact single-word field into complicated data structure like array. Please consider avoiding that unless there are some other reasons (external API constraint like JSON serialization) or significant readability gain.
As intermediate approach you can create small wrapper structure that holds integer value and additionally exposes indexed access to each bit (preferably immutable).
If you really want and array - basic for loop or LINQ can be used to transform each bit into boolean. I.e. If it is just one integer (may need to adjust order depending which bit you need first, this one puts lowest bit first):
var array = Enumerable.Range(0, 32)
.Select(bitNumber => (Forced & (1 << bitNumber)) !=0)
.ToArray();
public static class UIntExtensions
{
public static byte[] GetBitArray(this uint v)
{
var r = byte[32];
for (var i = 0; i < 32; ++i)
{
r[i] = v & 1;
v = v >> 1
}
return r;
}
}
In C++ I can use compiler specific intrisics to find the left|right most bit set, like shown in this thread.
Is there anything similar in C#? Or I need to iterate over all the bits to achieve that?
Here you go. Implementations adapted from here.
// Implementation of Least|Most SigBitSet from http://aggregate.org/MAGIC/
using System;
namespace Demo
{
internal class Program
{
private static void Main()
{
int value = 0x0ff0; // 0000111111110000
Console.WriteLine(LeastSigBitSet(value).ToString("x")); // 0x0010
Console.WriteLine(MostSigBitSet(value).ToString("x")); // 0x0800
}
public static int LeastSigBitSet(int value)
{
return (value & -value);
}
public static int MostSigBitSet(int value)
{
value |= (value >> 1);
value |= (value >> 2);
value |= (value >> 4);
value |= (value >> 8);
value |= (value >> 16);
return (value & ~(value >> 1));
}
}
}
And the unsigned int version (probably the one you will want):
using System;
namespace Demo
{
internal class Program
{
private static void Main()
{
uint value = 0x00ffff00; // 00000000111111111111111100000000
Console.WriteLine(LeastSigBitSet(value).ToString("x")); // 0x0000100
Console.WriteLine(MostSigBitSet(value).ToString("x")); // 0x0800000
}
public static uint LeastSigBitSet(uint value)
{
return (value & 0u-value);
}
public static uint MostSigBitSet(uint value)
{
value |= (value >> 1);
value |= (value >> 2);
value |= (value >> 4);
value |= (value >> 8);
value |= (value >> 16);
return (value & ~(value >> 1));
}
}
}
There is no access to compiler-specific "builtin" instructions for things like ffs. You would have to use a regular code implementation using things like bitmasks and shift operations. However, that doesn't necessarily mean you need to iterate over all the bits: there are some scary-clever "regular" implementations for many of these methods, doing crazy "add some bizarre constant that isn't obvious" that are designed to cut out most of the branching and iteration, and which would be perfectly fine in C#. The main thing to keep in mind if you port one of these is knowing whether it is using "signed" or "unsigned" right-shifts; if it is using "signed" use int (etc); if it is "unsigned", use uint (etc).
You can use BitOperations.LeadingZeroCount() and BitOperations.TrailingZeroCount(). They use hardware intrinsics when available.
Lots of people with complicated solutions here... He said "efficient", so I'd go with these if they'll do the trick for you.
lsb=i&-i;
msb=(int)(((double)i >> 20) - 1023);
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 >).
There is a nice way of figuring out the enumeration element using the following approach:
// memberType is enum type
if (Enum.IsDefined(memberType, valueString))
{
return Enum.Parse(memberType, valueString);
}
else
{
try
{
var underlyingValue = Convert.ChangeType(valueString, Enum.GetUnderlyingType(memberType));
if (Enum.IsDefined(memberType, underlyingValue))
{
return underlyingValue;
}
}
catch...
}
This works like charm. Except for values built from enumerations marked with FlagsAttribute. For example, for this enum and a value:
[Flags]
enum MyEnum {
One = 0x1,
Two = One << 1,
Four = One << 2,
Eight = One << 3
}
var e = MyEnum.One | MyEnum.Eight;
the approach above doesn't work. Looks like the only way to make it work is to try to get all the enum values and bitwise AND them with the input value. That's somewhat tedious though. So do you know any better way?
Answer:
The final method looks like this:
var parsed = Enum.Parse(memberType, valueString);
decimal d;
if (!decimal.TryParse(parsed.ToString(), out d))
{
return parsed;
}
throw new ArgumentOutOfRangeException(memberInfo.Name, valueString, "Bad configuration parameter value.");
I guess a better question to ask, how to detect bad values.
Looks like there is a nice work around found in C# 4.0 in a Nutshell. From here. Once you Parse the integer value to the enum, you can use this and see if the value is valid. This will work for combined flags.
static bool IsFlagDefined(Enum e)
{
decimal d;
return !decimal.TryParse(e.ToString(), out d);
}
This is expected behavior, as you can get values that do not correspond to the flags. For example, let's assume value a = 1, b = 2, c = 4, d= 8, etc. (Just standard binary progression). It is possible to have a 5 for the value (a & c) or 7 (a, b & c).
Why don't you just use Enum.Parse()
var test = MyEnum.One | MyEnum.Eight;
var str = test.ToString();
var back = (MyEnum) enum.Parse(typeof(MyEnum), str); // this returns MyEnum.One | MyEnum.Eight
First try to convert your string to "undelying type", if succeded - cast it to MyEnum and that's what you needed.
If convert failed - try to use Enum.Parse.
If it also fails - that is a very bad input (throw exception)
Update:
No testing for int conversion is needed enum.Parse(typeof(MyEnum), "9") returns MyEnum.One | MyEnum.Eight (tested in Framework 2.0 to 4.0)
Update 2:
So question really was "How to figure out bad values?". Dirty solution:
var res = Enum.Parse(targetType, str);
bool isBad;
try
{
Convert(res.ToString(), underType);
isBad = true;
}
catch
{
// convert failed
isBad = false;
}
if (isBad)
throw new Exeption();
return res;
But it is very dirty and throwing exception is expensive operation so there is performance penalty here... But it works)
Use Enum.Parse. Then check on the returned value, that no bits are set that are not valid flags. To do this, make a bitmask containing all the valid values, and OR them together with the value. If the result differs from the mask, some bits was set, that are not valid flags. This is not too tedious (but you will need to check whether the Enum is in fact a Flags enum, before applying this logic - if it is not a Flags enum, use IsDefined).
The code could go something like this; and you could store the mask per type pre-computed if you think it might be too expensive to calculate each time (it's probably not, but will depend on your case):
object value = Enum.Parse(memberType, valueString);
int numericValue = (int)value;
int definedMask = Enum.GetValues(memberType).Cast<int>().Aggregate(0, (v,a) => v | a);
if ((definedMask | numericValue) != definedMask)
throw new InvalidOperationException(String.Format("{0} is not a valid {1} value.", valueString, memberType.Name));
return value;
That is a nice question, your suggestion
try to get all the enum values and
bitwise AND them with the input value
after 10 minutes of research looks really reasonable.. ^^
I found a nice link regarding similar issue, a guy there spent quite some time to write this article, maybe you will find it interesting too.
Breaking down C# Flags enums into individual values for comparison
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