+ 1
Bitwise '|=' differences with bool and int
Correct me if its wrong: for bools bool_var |= other_bool Equals to "if at least one of both is true, then true". But what if one or both are int? It depends if the one being modified is int or bool? Something to know about other types? Thank you
5 Answers
+ 10
Kiwwi# I've updated my original answer for clarity.
Checkout line 32 in this simple example using the operator { |= } to store all possible enum values in a single integral value.
meetingDays |= Day.Friday;
Here... a single value can be used to determine all meetingDays. It does this by dedicated bit value assignment based on bit position.
This is only a simple example.
https://code.sololearn.com/c91AP4gTOW8z/?ref=app
+ 5
Kiwwi# In C#, a |= b uses a compound bitwise OR assignment operator { |= } on integral types to flip all respective ON bits in either {a} or {b} .
It's shorthand for:
a = a | b;
Consider the bitwise OR on the following values:
var a = 1; //0001 (binary)
var b = 0; //0000 (binary)
a |= b is 1 because at least one bit in the first position is ON with {a} and {b}. (0001)
Consider this for integral values using different bit positions:
var a = 1; //0001 (binary)
var b = 4; //0100 (binary)
a |= b is 5 //0101 (binary)
{a} changes from 4 to 5 because {b} introduces a new ON bit in the 3rd bit position.
Consider values with overlapping bit positions:
var a = 5; //0101 (binary)
var b = 4; //0100 (binary)
a |= b is 5 //0101 (binary)
Here, {a} remains 5 because no new bits were turned ON in {b}.
0
David Carroll
Then what's the logic behind use |= with integers; how its supposed that must be used?
Martin Taylor
then isn't used with real nums?