Represent a Number as a Binary in C# - c#

I have four checkboxes and user can select any check box and I want to store checked checkboxes in a single value. Logic should be like
Item Value
Checkbox1 1
Checkbox2 2
Checkbox3 4
Checkbox4 8
If a user selects Checkbox1 and Checkbox2 then it should be stored 3 If select Checkbox1, Checkbox2 and Checkbox3 then it should be stored 7. It will store some of value. Now I want to derive selected checkboxes from stored value, that means if a value is 7 then Checkbox1, Checkbox2 and Checkbox3 are selected.
How can I achieve this? If any can help me on this.

To determine which checkboxes should be checked, use the bitwise AND operator:
Checkbox1.Checked = value & 1;
Checkbox2.Checked = value & 2;
Checkbox3.Checked = value & 4;
Checkbox4.Checked = value & 8;

use an enum with the Flags attribute:
[Flags]
public enum CheckBoxEnum
{
Value1 = 1,
Value2 = 2,
Value3 = 4,
Value4 = 8,
}
You can then check the results using bitwise operations:
var res = CheckBoxEnum.Value1 | CheckBoxEnum.Value2;
var res2 = CheckBoxEnum.Value1 & CheckBoxEnum.Value2;

UPD:
#Glorfindel answer is more elegant, but you should use Bitwise OR instead of AND
Checkbox1.Checked = value | 1;
Checkbox2.Checked = value | 2;
Checkbox3.Checked = value | 4;
Checkbox4.Checked = value | 8;
You are looking for FlagsAttribute, applied to Enum
[Flags]
public enum CheckboxesSelected
{
Checkbox1 = 1,
Checkbox2 = 2,
Checkbox3 = 4,
Checkbox4 = 8
}
Then:
if your checkboxes controls is selected, you can do something like this:
CheckboxesSelected result = CheckboxesSelected.Checkbox1 | CheckboxesSelected.Checkbox2; //result will be 3

Related

Setting enum flags from integer value

CompBitsList companyBit;
public CompBitsList CompanyBit { get => companyBit; set => companyBit= value; }
[Flags]
public enum CompBitsList
{
None = 0
BitOption1 = 1,
BitOption2 = 2,
BitOption3 = 4,
BitOption4 = 8,
BitOption5 = 16,
BitOption6 = 32,
}
Lets say I have the integer value 22 that would contain the enum flags BitOption2, BitOption3 and BitOption5 (2+4+16). Is there a way to automate this so that I can pass the integer value and have the enum variable CompanyBit set automatically?
companyBit = CompBitsList.BitOption2 | CompBitsList.BitOption3 | CompBitsList.BitOption5
I'm not very familar with enums but I would prefer not to do the method above so any suggestions are appreciated. Thanks :)
You can just cast the int to an instance of CompBitsList.
CompBitsList companyBit = (CompBitsList)22;
companyBit.HasFlag(CompBitsList.BitOption2); // True
companyBit.HasFlag(CompBitsList.BitOption3); // True
companyBit.HasFlag(CompBitsList.BitOption5); // True
companyBit.HasFlag(CompBitsList.BitOption6); // False
You can also define a value on that enum that represents a combination of flags, if it makes sense and you'll be combining those flags a lot.
[Flags]
public enum CompBitsList
{
None = 0
BitOption1 = 1,
BitOption2 = 2,
BitOption3 = 4,
BitOption4 = 8,
BitOption5 = 16,
BitOption6 = 32,
BitOptions2And3And5 = BitOption2 | BitOption3 | BitOption5 //or just 22
}

Enum.HasFlag is not working as expected [duplicate]

This question already has answers here:
HasFlag always returns True
(5 answers)
Closed 4 years ago.
I have a Enum with Flags like this:
[Flags]
public enum ItemType
{
Shop,
Farm,
Weapon,
Process,
Sale
}
Then I have several objects in a list with some flags set and some flags not set. It looks like this:
public static List<ItemInfo> AllItems = new List<ItemInfo>
{
new ItemInfo{ID = 1, ItemType = ItemType.Shop, Name = "Wasserflasche", usable = true, Thirst = 50, Hunger = 0, Weight = 0.50m, SalesPrice = 2.50m, PurchasePrice = 5, ItemUseAnimation = new Animation("Trinken", "amb#world_human_drinking#coffee#female#idle_a", "idle_a", (AnimationFlags.OnlyAnimateUpperBody | AnimationFlags.AllowPlayerControl)) },
new ItemInfo{ID = 2, ItemType = ItemType.Sale, Name = "Sandwich", usable = true, Thirst = 0, Hunger = 50, Weight = 0.5m, PurchasePrice = 10, SalesPrice = 5, ItemUseAnimation = new Animation("Essen", "mp_player_inteat#pnq", "intro", 0) },
new ItemInfo{ID = 3, ItemType = (ItemType.Shop|ItemType.Process), Name = "Apfel", FarmType = FarmTypes.Apfel, usable = true, Thirst = 25, Hunger = 25, Weight = 0.5m, PurchasePrice = 5, SalesPrice = 2, ItemFarmAnimation = new Animation("Apfel", "amb#prop_human_movie_bulb#base","base", AnimationFlags.Loop)},
new ItemInfo{ID = 4, ItemType = ItemType.Process, Name = "Brötchen", usable = true, Thirst = -10, Hunger = 40, Weight = 0.5m, PurchasePrice = 7.50m, SalesPrice = 4}
}
Then I go trough the list with a loop and ask if the flag ItemType.Shop is set or not, like this:
List<ItemInfo> allShopItems = ItemInfo.AllItems.ToList();
foreach(ItemInfo i in allShopItems)
{
if (i.ItemType.HasFlag(ItemType.Shop))
{
API.consoleOutput(i.Name);
}
}
This is the output of my loop - it shows all items in the list, and the .HasFlag method always returns true in this case.
Wasserflasche
Sandwich
Apfel
Brötchen
Try to assign values to your enum
[Flags]
public enum ItemType
{
Shop = 1,
Farm = 2,
Weapon = 4,
Process = 8,
Sale = 16
}
Here are some Guidelines for FlagsAttribute and Enum (excerpt from Microsoft Docs)
Use the FlagsAttribute custom attribute for an enumeration only if a bitwise operation (AND, OR, EXCLUSIVE OR) is to be performed on a numeric value.
Define enumeration constants in powers of two, that is, 1, 2, 4, 8, and so on. This means the individual flags in combined enumeration constants do not overlap.
You should assign values to your enums. All the flags attribute does is change how the ToString method works. I would use a bitwise operator to make it less likely to make a mistake:
[Flags]
public enum ItemType
{
Shop = 1 << 0, // == 1
Farm = 1 << 1, // == 2
Weapon = 1 << 2, // == 4
Process = 1 << 3, // == 8
Sale = 1 << 4 // == 16
}

Loop through enum result property

I have a model with a enum property. When I call my service, the model is returned back, and my enum-property contains the following data: Test1 | Test2 | Test3.
I want to loop through the propery and assign the values to a list.
How can I do this with an enum propery?
var form = await _formService.GetById();
That code above generates a result with a enum property called Sections with th data that I provided above, but I don't know how to loop through It to get the values.
Here is my Enum:
[Flags]
public enum Sections
{
Test1= 0,
Test2= 1,
Test3= 2,
Test4= 4,
}
Is this what you are looking for?
[Flags]
public enum Sections
{
Test1 = 0,
Test2 = 1,
Test3 = 2,
Test4 = 4,
}
public static List<Sections> getSectionsFromFlags(Sections flags)
{
var returnVal = new List<Sections>();
foreach (Sections item in Enum.GetValues(typeof(Sections)))
{
if ((int)(flags & item) > 0)
returnVal.Add(item);
}
return returnVal;
}
If you have defined enum like this
[Flags]
public enum Sections
{
Test1 = 0,
Test2 = 1,
Test3 = 2,
Test4 = 4,
}
Then
var someValue = Sections.Test1 | Sections.Test3 | Sections.Test4;
var values = Enum.GetValues(typeof(Sections))
.OfType<Sections>().Where(x=>(x&someValue)==x)
.ToArray();
values now contains all three value Sections.Test1 | Sections.Test3 | Sections.Test4
Another solution (from comments)
var values = Enum.GetValues(typeof(Sections))
.OfType<Sections>()
.Where(x=>someValue.HasFlag(x))
.ToArray();
Last one Is most correct, I think.

where is the enum declared from user input c#

I have two enums and I want to determine from user input(string), in which array is the enum with the same name from user input
public enum LengthUnit
{
mm = -3,
cm = -2,
dm = -1,
m = 0,
km = 3
}
public enum NumericUnit
{
b = 2,
o = 8,
d = 10,
h = 16
}
string input = "cm";
Sounds like you want Enum.TryParse which will let you pass a string and the enum type as parameters and an out parameter as the result if the TryParse succeeds.

winform - setting Selected value of listbox

I had a list box called listbox1 will bounded to list like this:
ValueVM word1 = new ValueVM { Id = 1, Name = "AAA" };
ValueVM word2 = new ValueVM { Id = 2, Name = "XBB" };
ValueVM word3 = new ValueVM { Id = 3, Name = "ACC" };
ValueVM word4 = new ValueVM { Id = 4, Name = "ACB" };
ValueVM word5 = new ValueVM { Id = 5, Name = "OTD" };
ValueVM word6 = new ValueVM { Id = 6, Name = "FDD" };
var li = new List<ValueVM>() { word1, word2, word3, word4, word5, word6 };
listBox1.DataSource = li.OrderBy(l=>l.Name).ToList();
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "Id";
I want to one Item to be seleted in this list box, suppose I want the Id=2;
int myID = 2;
//Idont know what the selected index will be but I need the selected value to be set
// I tried to set listBox1.SelectedValue=myId.ToString();
//but still returning null
listBox1.SelectedValue = myID;
as mentioned in MSDN:
Gets or sets the value of the member property specified by the ValueMember property. (Inherited from ListControl.)
my problem that seleted value get the value from value member but it didn't set the value?
any Ideas?
You're in the right direction only. SelectedValue should do what you need.
listBox1.SelectedValue = 2;//this works for me
Note: You've to set the int here since datasource is int. setting "2" won't work
Try with
listBox1.SetSelected(MyId, true);
Take a look at this
you should change yourcode into someting like this
listBox1.DataSource = li.OrderBy(l=>l.Name).ToArray();
because the datasource does not understand IOrderedEnumerable
Hopethis help

Categories