How is working binary operation and boolean conversion? - c#

I have this code :
int flags = some integer value;
compte.actif = !Convert.ToBoolean(flags & 0x0002);
It is working very well the problem is I don't really understand how it s working..
The & operation is a bitwise AND I assume so Imagine 110110 & 000010 I assume it will result 001011 (maybe i'm wrong from here). The goal is to check if the 2's bit in the first term is filled. So in this case it is true.
I don't really understand How it can be converted in boolean..
Thanks for help

Bitwise and of 110110 & 000010 is 000010.
The ToBoolean looks for a non-zero value, so basically, this code checks that flags has the 2nd bit set, then negates it (!). So it is checking "is the 2nd bit clear".
A more traditional test there might be:
compte.actif = (flags & 0x02) == 0;

The bitwise AND operation will give you an integer containing bits that were set on both numbers. I.e. 0b110011 & 0b010100 yields 0b010000.
The exclamation mark switches the boolean, causing true only of the 2nd bit is NOT set.

Related

Use of Bitwise AND (&) in this scenario

I've seen some explanations of & (and plenty of explanations of |) around SO (here etc), but none which clarify the use of the & in the following scenario:
else if ((e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move) {...}
Taken from MSDN
Can anyone explain this, specific to this usage?
Thanks.
e.AllowedEffect is possibly a combination of bitwise flags. The & operator performs a bit a bit "and" logical operation with each bit. As a result if the bit under test is one, the result is that single flag.
The test could be writter in this way with exactly the same result:
else if ((e.AllowedEffect & DragDropEffects.Move) != 0 ) {...}
Lets explain better with an example, the flag value are these:
None = 0,
Copy = 1,
Move = 2,
Link = 4,
So in binary:
None = 00000000,
Copy = 00000001,
Move = 00000010,
Link = 00000100,
So we consider the case in which under test we have the combination of Copy and Move, ie the value will be:
00000011
by bitwise and with move we have:
00000011 -->Copy | Move
00000010 -->Move
======== &
00000010 === Move
Suppose :
DragDropEffects.Move has 1 value.
e.AllowedEffect has 0 value.
It will do bitwise AND (1 & 0 = 0) of the 2 hence the result will be 0 currently:
DragDropEffects.Move & e.AllowedEffect will be 0 in this case.
Consider this now :
DragDropEffects.Move has 1 value.
e.AllowedEffect has 1 value.
in that case bitwise AND will return 1 (as 1 & 1 = 1 in bitwise AND) so now the result will be 1.
Bitwise AND will return 0 if one of the bit is 0 which we are doing AND and will return 1 if all are set to 1.
The second answer in this post which you linked in your question explains it well.
DragDropEffects.Move has one bit set, the second least significant making it the same as the number 2.
If you & something with 2 then if that bit is set you will get 2 and if that bit is not set, you will get 0.
So (x & DragDropEffects.Move) == DragDropEffects.Move will be true if the flag for DragDropEffects.Move is set in x and false otherwise.
In languages which allow automatic conversion to boolean it's common to use the more concise x & DragDropEffects.Move. The lack of concision is a disadvantage with C# not allowing such automatic conversion, but it does make a lot of mistakes just not happen.
Some people prefer the alternative (x & DragDropEffects.Move) != 0 (and conversely (x & DragDropEffects.Move) == 0 to test for a flag not being set) which has the advantage of 0 working here no matter what the enum type or what flag is tested. (And potentially a minor advantage in resulting in very slightly smaller CIL if it is turned straight into a brzero instruction, but I think it generally doesn't anyway).
DragDropEffects is not just enum, this is a set of flags, so in your example we check whether e.AllowedEffect has set bits for DragDropEffects.Move or not.
hope you understand how bitwise operators work.
if e.AllowedEffect is set to DragDropEffects.Move then their & will result in either e.AllowedEffector DragDropEffects.Move i.e.
e.AllowedEffect = 1
DragDropEffects.Move = 1
e.AllowedEffect & DragDropEffects.Move = 1
from the MSDN example, it rouhhly means:
'if ActiveEffect is set/equal to DragDropEffects.Move then do this...'

When is a shift operator >> or << useful? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When to use Shift operators << >> in C# ?
I've in programming a while and I've never used the shift operator. I could see how it could be helpful for calculating hash codes like in Tuple<T>, but other than that,
When and how is the shift operator useful in C#/.NET?
In general it's not used very often. But it's very useful when dealing with bit level operations. For example printing out the bits in a numeric value
public static string GetBits(int value) {
var builder = new StringBuilder();
for (int i = 0; i < 32; i++) {
var test = 1 << (31 - i);
var isSet = 0 != (test & value);
builder.Append(isSet ? '1' : '0');
}
return builder.ToString();
}
It's useful to write powers of two.
Quick: What's 227?
Answer: 1 << 27
Writing 1 << 27 is both easier and more understandable than 134217728.
I use it rather a lot in dealing with hardware. This isn't something you probably do in C# a lot, but the operator was inherited from C/C++ where it is a fairly common need.
Example 1:
I just got a longword from a little-endian machine, but I'm big endian. How do I convert it? Well, the obvious is call htonl() (you cheater). One of the manual ways to do it is with something like the following:
((source & 0x000000ff) << 24 ) |
((source & 0x0000ff00) << 8) |
((source & 0x00ff0000) >> 8) |
((source & 0xff000000) >> 24);
Example 2:
I have a DMA device that only allows longword accesses of up to 512K. So it requires me to put (for reasons only understood by hardware folks) the modulo 4 of the transfer size into the high order 18 bits of a DMA transfer control register. For the sake of arguement, the low-order bits are to be filled with various flags controlling the DMA operation. That would be accomplished like so:
dma_flags | ((length & 0xffffc) << 14);
These might not be the kind of things you do every day. But for those of us that regularly interface to hardware they are.
If you ever need to multiply without using * How to implement multiplication without using multiplication operator in .NET :)
Or write a Sudoku solver Sudoku validity check algorithm - how does this code works?
In practice, the only time I've seen it used in my (limited) experience was as an (arguably) confusing way to multiply (see first link) or in conjunction with setting BitFlags (the Sudoku solver above).
In .NET I rarely have to work at the bit level; but if you need to, being able to shift is important.
Bitwise operators are good for saving space, but nowadays, space is hardly an issue.
It's useful when multiplying by powers of 2
number<<power;
is number*2^power
And of course division by powers of 2:
number>>power;
Another place is flags in enums.
when you come across code like
Regex re = new Regex(".",RegexOptions.Multiline|RegexOptions.Singleline);
the ability to use RegexOptions.Multiline|RegexOptions.Singleline i.e multiple flags is enabled through the shifting and also this allows them to be unique.
Something like:
enum RegexOptions {
Multiline = (1 << 0),
Singleline = (1<<1)
};
Bit shifts are used when manipulating individual bits is desired. You'll see a lot of bit shifts in many encryption algorithms, for example.
In optimization, it can used in place of multiplication/division. A shift left is equal to multiplying by two. Shift right equals division. You probably don't see this done anymore, since this level of optimization is often unnecessary.
Other than that, I can't think of many reasons to use it. I've seen it used before, but rarely in cases where it was really required and usually a more readable method could have been used.
Whenever you need to multiply by 2 ;)
Really the only use I have is for interoperability code and bitfields:
http://www.codeproject.com/KB/cs/masksandflags.aspx

How does a logical & work on two bytes in C#?

I recently had a test question:
byte a,b,c;
a = 190;
b = 4;
c = (byte)(a & b);
What is the value of c?
I have never used a logical operand in this manner, what's going on here? Stepping through this, the answer is 4, but why?
Also, where would this come up in the real world? I would argue that using logical operands in this manner, with a cast, is just bad practice, but I could be wrong.
You are doing a bitwise AND in this case, not a logical AND, it is combining the bits of the two values of a & b and giving you a result that has only the bits set that are both set in a & b, in this case, just the 4s place bit.
190 = 10111110
& 4 = 00000100
-------------------
= 4 00000100
Edit: Interestingly, msdn itself makes the issue of whether to call it logical vs bitwise a bit muddy. On their description of the logical operators (& && | || etc) they say logical operators (bitwise and bool) but then on the description of & itself it indicates it performs a bitwise AND for integers and a logical AND for bools. It appears it is still considered a logical operator, but the action between integer types is a bitwise AND.
http://msdn.microsoft.com/en-us/library/sbf85k1c(v=vs.71).aspx
The logical AND operator, when applied to integers performs a bitwise AND operation. The result is 1 in each position in which a 1 appears in both of the operands.
0011
& 0101
------
0001
The decimal value 190 is equivalent to binary 10111110. Decimal 4 is binary 00000100.
Do a logical AND operation on the bits like this:
10111110
& 00000100
----------
00000100
So the result is 4.
Also, where would this come up in the real world? I would argue that using logical operands in this manner, with a cast, is just bad practice, but I could be wrong.
These operations are useful in several circumstances. The most common is when using Enum values as flags.
[Flags]
public enum MyFileOptions
{
None = 0,
Read = 1, // 2^0
Write = 2, // 2^1
Append = 4, // 2^2
}
If an Enum has values that are powers of two, then they can be combined into a single integer variable (with the Logical OR operator).
MyFileOptions openReadWrite = MyFileOptions.Read | MyFileOptions.Write;
In this variable, both bits are set, so it indicates that both the Read and Write options are selected.
The logical AND operator can be used to test values.
bool openForWriting = ((openReadWrite & MyFileOptions.Write) == MyFileOptions.Write);
NOTE
A lot of people are pointing out that this is actually a bitwise AND not a logical AND. I looked it up in the spec before I posted, and I was suprised to learn that both versions are referred to as "Logical AND" in the spec. This makes sense because it is performing the logical AND operation on each bit. So you are actually correct in the title of the question.
This is a bitwise AND, meaning the bits on both bytes are compared, and a 1 is returned if both bits are 1.
10111110 &
00000100
--------
00000100
One of the uses of a logical & on bytes is in networking and is called the Binary And Test. Basically, you logical and bytes by converting them to binary and doing a logical and on every bit.
In binary
4 == 100
190 == 10111110
& is and AND operation on the boolean operators, so it does de Binary and on 4 and 190 in byte format, so 10111110 AND 100 gives you 100, so the result is 4.
This is a bitwise AND, not a logical AND. Logical AND is a test of a condition ie:
if(a && b) doSomething();
A bitwise AND looks at the binary value of the two variables and combines them. Eg:
10101010 &
00001000
---------
00001000
This lines up the binary of the two numbers, like this:
10111110
00000100
--------
00000100
On each column, it checks to see if both numbers are 1. If it is, it will return 1 on the bottom. Otherwise, it will return 0 on the bottom.
I would argue that using logical operands in this manner, with a cast, is just bad practice, but I could be wrong.
There is no cast. & is defined on integers, and intended to be used this way. And just so everyone knows, this technically is a logical operator according to MSDN, which I find kind of crazy.

C# strange code

Anyone know what follow code does?
the question is about follow operators: & and |,and 0xfc
salt[0] = (byte)((salt[0] & 0xfc) | (saltLen & 0x03));
salt[1] = (byte)((salt[1] & 0xf3) | (saltLen & 0x0c));
salt[2] = (byte)((salt[2] & 0xcf) | (saltLen & 0x30));
salt[3] = (byte)((salt[3] & 0x3f) | (saltLen & 0xc0));
the question is about follow operators: & and |,and 0xfc
& is the bitwise and operator. See http://msdn.microsoft.com/en-us/library/sbf85k1c.aspx.
| is the bitwise or operator. See http://msdn.microsoft.com/en-us/library/kxszd0kx.aspx.
0xfc isn't an operator, it's an integer constant (i.e., a number). See http://msdn.microsoft.com/en-us/library/aa664674(VS.71).aspx and http://en.wikipedia.org/wiki/Hexadecimal.
Well the comment above explains what it's doing, but if you're looking for a breakdown of the operators:
Perform a bitwise and on
salt[i] and a hex number (the & operator).
Perform a bitwise and on salt[i]
and a second hex number.
Perform a bitwise or on the result of steps 1 and 2 (the | operator).
Cast the result of step 3 to a byte
Store the result in salt[i]
The result is what is noted in the comment block. The numbers of the format 0xc0 and whatnot are in hexadecimal, which is base 16. I.e. c0 in hex is equivalent to 16*12 + 16*0 = 192 in decimal. In hex, since you run out of digits at 9, you begin using letters. Thus, a=10, b=11, c=12, d=13, e=14, f=15, and f becomes the highest "digit" since you would move over by one place when you get to 16 (as 16 is the base).
See also:
Bitwise operation
Hexadecimal
// Split salt length (always one byte) into four two-bit pieces and
// store these pieces in the first four bytes of the salt array.
This is a cocky answer, but my intention is to indicate that it is already answered, so please let me know if you need more detail :)

Long type, left shift and right shift operations

Continuing my previous question
Why I cannot derive from long?
I found an interesting problem.
Step one:
4294967296 & 0xFFFFFFFF00000000
Result: 4294967296.
Step two.
4294967296 & 0x00000000FFFFFFFF
Result: 0
Aha, So here I assume that 4294967296 == 0xFFFFFFFF
Let's check
(long)0x00000000FFFFFFFF
Result: 4294967295. Fail.
Let's double check
4294967296 >> 32
Result: 1. Fail.
The only explanation is that because i am using long where
some bit is reserved for sign. In C I would use unsigned long.
What do you think guys?
4294967296 & 0xFFFFFFFF00000000 = 4294967296
This indicates that the value 4294967296 has no bits set in the lower 32-bits. In fact, 4294967296 is 0x100000000, so this is true.
4294967296 >> 32 = 1
Again, consistent.
In other words, your conclusion that 4294967296 is 0xFFFFFFFF is wrong so the remaining checks will not support this.
Um... I'm not sure why you came to the conclusions you did but 4294967296 is 0x100000000. To write out the bitwise AND's in easily readable hex...
0x0000000100000000 &
0x00000000FFFFFFFF =
0x0000000000000000
0x0000000100000000 &
0xFFFFFFFF00000000 =
0x0000000100000000
Both of those make perfect sense. Perhaps you're misunderstanding a bitwise AND... it maps the bits that are the same in both. Your comments seem more appropriate to a bitwise XOR than a bitwise AND (Which is not the operation you're using)...
I think you are failing to understand the bitwise and operation. The bitwise and will return the bits that are set in both. If the two were the same then
(4294967296 & 0xFFFFFFFF00000000) == 4294967296
and
(4294967296 & 0xFFFFFFFF00000000) == 0xFFFFFFFF00000000
would both hold, but they obviously don't.

Categories