How to interpret condition with comparing result of binary operator? - c++

I have this code:
if((bob.prop & 0x100) == 0x100) {
// some code
}
I found that this part:
bob.prop & 0x100
means
is bob.prop set to 0x100?
So, I think it gives me true or false. But the result of this code is comparing with 0x100 also:
if((bob.prop & 0x100) == 0x100) {
What is it? What does it mean?

0x100 in binary is 0000000100000000, which has its 9th bit set.
Doing bob.prop & 0x100 filters out that 9th bit from bob.prop. For example:
bob.prop & 0x100
1010110101110010 & 0000000100000000 gives 0000000100000000
0110110001101011 & 0000000100000000 gives 0000000000000000
It does this because it is the bitwise AND of the two operands. That means the result will only have bits set where bits are set in both of the operands.
You are then checking whether the result is equal to 0000000100000000, which is the same as asking "Was the 9th bit set?"
It is not necessary to perform this final comparison, because any integer value greater than 0 will convert to true, while 0 will convert to false. You could just write:
if(bob.prop & 0x100)

the bob.prop & 0x100 is doing a bitwise and of bob.prop with 0x100. The if statement is ensuring that equals 0x100.
So the first test is evaluating an expression, and putting it in the if checks if it matches 0x100.
Note that you are not testing that bob.prop is set to 0x100, rather than are checking whether one bit is set. So the expression would be true for input of 0x100, 0x101, 0x102, 0xfff, ...

Related

What does the "uFlags &= ~CHN_PANNING" command do?

What does this command mean in a .c/.cpp file?
uFlags &= ~CHN_PANNING;
as per my research uFlags are Bit-Wise flags.
~ is bit negation. It turns 011001 into 100110, etc. If you & with the bit negation of a number, you essentially remove the 1-bits of the right hand side from the bits on the left hand side (1s turn to 0s after the bit negation and no bit can stay 1 if it's &-ed with 0. 0s turn to 1s and &-ing with 1 doesn't change the original bit).
bitset0 &=~ bitset1 (or bitset0 &~ bitset) is therefore a kind of a C/C++ idiom for (bit)set subtraction. It subtracts bitset1 from bitset0 (i.e. bitset0 \ bitset1 in math notation), possibly (in the = version) assigning the result to bitset0.
The bitwise-AND assignment operator &= gives to the expression
uFlags &= ~CHN_PANNING;
the same meaning as
uFlags = uFlags & ~CHN_PANNING;
Now, the & bit-wise operator is used to reset (clear) all those bits of flags to 0, witch have the corresponding bit of the mask reset (cleared) to 0. Other bits of flags remain unchanged.
For example:
11001011 (flags)
&
10101110 (mask)
-------------------
10001010 (result)
Unary operator ~ is the negation - it switches bits with value 0 to 1 and vice versa. It means that your mask ~CHN_PANNING will reset (clear) to 0 that bit (or those bits), which were set (to 1) in the original CHN_PANNING.

The significance of `&` operator in this C++ code

I saw some code like this:
void testCase2 (int variant)
{
if (variant & 0x1)
{
return;
}
}
What does the & operator mean in the if statement, is it ==? Why to use &?
& is the bitwise AND operator. Given two integer operands, it does an AND operation on each bit position, i.e. in the result only those bits will be set that were set in both operands.
If one of the operands is 0x1 as in this case, the result will be 0x1 if, and only if, that bit is also set in the other operand (here, variant).
As C/C++ considers any non-zero integer to be true,
if (variant & 0x1)
checks if the least-significant bit in variant is set.
Similarly,
if (variant & 0x2)
would check if the second least-significant bit in variant is set, and
if (variant & 0x3)
would check if either of the two least-significant bits in variant is set.
It's a "bitwise and", basically that code will check if the lowest significant bit in 'variant' is set.
The operator does an AND operation on each relative bit of the two items being compared to get the result. It's a common way to examine variables that are being used to carry multiple bit 'flags'.
as an example, "bitwise anding" two variables with these binary representations:
00010001
00000001
would give:
00000001
http://en.wikipedia.org/wiki/Bitwise_operation#AND
variant: 1011 Bitwise AND
0x1 : 0001
-------
0001
-------
Bitwise AND is used to Turn-Off bits.
The bitwise AND operator is a single ampersand: &. A handy mnemonic is that the small version of the boolean AND, &&, works on smaller pieces (bits instead of bytes, chars, integers, etc). In essence, a binary AND simply takes the logical AND of the bits in each position of a number in binary form.
SRC : refer here
& operator is the boolean arithmetic AND operator i.e. bitwise AND
IN your code block, if (variant & 0x1) is evaluated as:
if (the result of ANDing variant and 0x1) is TRUE, them go inside the following block of code.
Consider the following code (see it in action on IDEONE):
#include <iostream>
using namespace std;
int main() {
int variant = 0x1f; // Declared in HEX format;
if (variant & 0x1){ // If the LSB is 1 i.e. if the
cout << "axious!!!"; // It'll print "axious!!!"
} else
{
cout << "It's something else!!!";
}
return 0;
}
But the following code:
#include <iostream>
using namespace std;
int main() {
int variant = 0x10; // Declared in HEX format;
if (variant & 0x1){ // If the LSB is 1
cout << "axious!!!";
} else
{
cout << "It's something else!!!"; // This will be printed!!
}
return 0;
}
Now remember that 0x1 will be 1 in binary i.e. the LSB will be 1 so you are actually checking for what is the first bit of your variant.

What is the difference between 'and' and '&' in C++?

#include <iostream>
int main(int argc, char* argv[])
{
unsigned long mask = 0x00000001;
unsigned long mask1 = 0x00000001;
unsigned long mask2 = 0x00000010;
if ((mask and mask1) && (mask and mask2))// CONDITION_1 is True.
std::cout << "Ohhhhhhh..." << std::endl;
if ((mask & mask1) && (mask & mask2)) //CONDITION_2 is False.
std::cout << "No Output..." << std::endl;
return 0;
}
I think CONDITION_1 and CONDITION_2 both are False, but my thinking is wrong obviously , why 'and' and '&' are not same in C++?
and and && are the same. It's logical and. & is bitwise and.
and or && is the logical AND operator. It yields true if both operands convert to true.
bitand or & is the bitwise AND operator. Each bit of the result is set if the corresponding bits of both operands are set.
The single ampersand is a bitwise and while the 'and' keyword is an alternative for &&, a logical and.
&& and and are both logical and operators, while & is the bitwise and operator.
So
(mask and mask1) && (mask and mask2)
is equivalent to
(mask && mask1) && (mask && mask2)
The 2 "and" operators in C/C++ are && (logical and) and & (bitwise and).
&& will return a boolean result (true/false, 1/0) if both arguments are non-zero (true) and false otherwise. This is used to determine if 2 boolean conditions are BOTH true.
& will return a integer with any bits set (1) in both arguments. So 0b10101010 & 0b11110000 will produce 0b10100000. This is useful for checking flags, or any other uses for bitmasks (especially in the embedded world, where you might use individual bits instead of full bytes/words/dwords for flags).
Edit: learned something new and removed an incorrect statement.
AND is logical short circuit && , while & is bitwise operator , working on individual bits.
When using the logical operators, C++ only evaluates what is necessary from left to right to come up with the combined relational result, ignoring the rest.
Bitwise operators modify variables considering the bit patterns that represent the values they store.
Here is some documentation.
& is the binary AND operator.
The result of this operator has only those bits set to 1 that are 1 in both arguments.
The result of ((mask and mask1) && (mask and mask2):
mask and mask1 == true (== mask && mask1)
mask and mask2 == true (== mask && mask2)
(true) && (true) == true
The result of (mask & mask1) && (mask & mask2):
mask & mask1 == 0x00000001 (since the least significant bit is 1 in both cases)
mask & mask2 == 0x00000000 (the bits that are 1 in mask are 0 in mask2 and vice versa)
(0x00000001) && (0x00000000) == false
AND is equivalent to && which is regarded as logical operator. And & is bitwise operator.
Bitwise AND(&)
The bitwise AND operator is a single ampersand: &. A handy mnemonic is that the small version of the boolean AND, &&, works on smaller pieces (bits instead of bytes, chars, integers, etc). In essence, a binary AND simply takes the logical AND of the bits in each position of a number in binary form.
For instance, working with a byte (the char type):
01001000
&
10111000
--------
00001000
The most significant bit of the first number is 0, so we know the most significant bit of the result must be 0; in the second most significant bit, the bit of second number is zero, so we have the same result. The only time where both bits are 1, which is the only time the result will be 1, is the fifth bit from the left. Consequently,
72 & 184 = 8
Logical AND(&&)
The logical AND operator is used to test whether both conditions are true. If both conditions are true, logical AND returns true. Otherwise, it returns false.

What is this doing: "input >> 4 & 0x0F"?

I don't understand what this code is doing at all, could someone please explain it?
long input; //just here to show the type, assume it has a value stored
unsigned int output( input >> 4 & 0x0F );
Thanks
bitshifts the input 4 bits to the right, then masks by the lower 4 bits.
Take this example 16 bit number: (the dots are just for visual separation)
1001.1111.1101.1001 >> 4 = 0000.1001.1111.1101
0000.1001.1111.1101 & 0x0F = 1101 (or 0000.0000.0000.1101 to be more explicit)
& is the bitwise AND operator. "& 0x0F" is sometimes done to pad the first 4 bits with 0s, or ignore the first(leftmost) 4 bits in a value.
0x0f = 00001111. So a bitwise & operation of 0x0f with any other bit pattern will retain only the rightmost 4 bits, clearing the left 4 bits.
If the input has a value of 01010001, after doing &0x0F, we'll get 00000001 - which is a pattern we get after clearing the left 4 bits.
Just as another example, this is a code I've used in a project:
Byte verflag = (Byte)(bIsAck & 0x0f) | ((version << 4) & 0xf0). Here I'm combining two values into a single Byte value to save space because it's being used in a packet header structure. bIsAck is a BOOL and version is a Byte whose value is very small. So both these values can be contained in a single Byte variable.
The first nibble in the resultant variable will contain the value of version and the second nibble will contain the value of bIsAck. I can retrieve the values into separate variables at the receiving by doing a 4 bits >> while taking the value of version.
Hope this is somewhere near to what you asked for.
That is doing a bitwise right shift the contents of "input" by 4 bits, then doing a bitwise AND of the result with 0x0F (1101).
What it does depends on the contents and type of "input". Is it an int? A long? A string (which would mean the shift and bitwise AND are being done on a pointer to the first byte).
Google for "c++ bitwise operations" for more details on what's going on under the hood.
Additionally, look at C++ operator precedence because the C/C++ precedence is not exactly the same as in many other languages.

C++ bit shifting

I am new to working with bits & bytes in C++ and I'm looking at some previously developed code and I need some help in understanding what is going on with the code. There is a byte array and populating it with some data and I noticed that the data was being '&' with a 0x0F (Please see code snipped below). I don't really understand what is going on there....if somebody could please explain that, it would be greatly apperciated. Thanks!
//Message Definition
/*
Byte 1: Bit(s) 3:0 = Unused; set to zero
Bit(s) 7:4 = Message ID; set to 10
*/
/*
Byte 2: Bit(s) 3:0 = Unused; set to zero
Bit(s) 7:4 = Acknowledge Message ID; set to 11
*/
//Implementation
BYTE Msg_Arry[2];
int Msg_Id = 10;
int AckMsg_Id = 11;
Msg_Arry[0] = Msg_Id & 0x0F; //MsgID & Unused
Msg_Arry[1] = AckMsg_Id & 0x0F; //AckMsgID & Unused
0x0f is 00001111 in binary. When you perform a bitwise-and (&) with this, it has the effect of masking off the top four bits of the char (because 0 & anything is always 0).
x & 0xF
returns the low four bits of the data.
If you think of the binary representation of x, and use the and operator with 0x0f (00001111 in binary), the top four bits of x will always become zero, and the bottom four bits will become what they were before the operation.
In the given example, it actually does nothing. Msg_Id and AckMsg_Id are both less than 0x0F, and so masking them has no effect here.
However the use of the bitwise-and operator (&) on integer types performs a bit for bit AND between the given operands.