strcat(b, ((x & z) == z) ? "1" : "0");
I understand strcat() function and the conditional (ternary) operator. But I don't know what (x & z) == z means.
& is the bitwise AND operator.
here, (x & z) == z means, perform a bitwise AND of x and z and if that value equals to z, then....
Ref: Chapter 6.5.10, C11 standard, "Bitwise AND operator"
The result of the binary & operator is the bitwise AND of the operands (that is, each bit in the result is set if and only if each of the corresponding bits in the converted operands is set).
The means:
Concatenate "1" to string b if bitwise And of x and z is same as z,else concatenate "0" to string b.
x&z means bitwise anding of x and z.
The result is then compared with z.
If the result is same as z then condition evaluates to be TRUE otherwise FALSE.
(x & z) == z means in 'x', ALL the bits which are SET in 'z' is SET.
'x' must contain all the bits set OR additionally some more bits may also be set. Then this condition becomes true.
Related
What is the difference between & and && in C?
My teacher gave me this example:
int a = 8;
int b = 4;
printf("a & b = %d\n", a & b);
printf("a && b = %d\n", a && b);
Output:
a & b = 0;
a && b = 1;
I'm not sure why this would return true in one scenario and false in another.
& is bitwise and and && is logical and.
The expression x && y will return 1 if both x and y is non-zero, and 0 otherwise. Note that if x is zero, then y will not be evaluated at all. This will matter if y is an expression with side effects. This behviour is called short circuiting.
The expression x & y will perform a bitwise operation on each individual bit in x and y. So if x is 1010 in binary and y is 1100 then x & y will evaluate to 1000. Note that the return value of x & y should NOT be interpreted as a Boolean value, even if it's possible. In early C, the operator && did not exist, and because of that & was used for this purpose.
One way to explain it is that you could imagine that & is the same thing as applying && on each individual bit in the operands.
Also note that & has lower precedence than &&, even though intuition says that it should be the other way around. This also goes for comparison operators, like <, <=, ==, !=, >=, >. This goes back to the time when C did not have the operators && and || and the bitwise versions was used instead. At this time, it made sense, but when the logical operators were added, it did not anymore. Kernighan and Ritchie admitted that it would have made more sense, but they did not fix it because this would break existing code.
I'm not sure why this would return true in one scenario and false in another.
The return value from x & y should not be treated as a Boolean value at all. However, it can (depending on how the code is written) be treated as a Boolean array. If you have two integers, flags1 and flags2 then the result of flags1 & flags2 will denote which flags that are toggled in both flags1 and flags2.
The & operator performs a bit-wise and operation on its integer operands, producing an integer result. Thus (8 & 4) is (0b00001000 bitand 0b00000100) (using a binary notation that does not exist in standard C, for clarity), which results in 0b00000000 or 0.
The && operator performs a logical and operation on its boolean operands, producing a boolean result. Thus (8 && 4) is equivalent to ((8 != 0) and (4 != 0)), or (true and true), which results in true.
&& (logical and operator) - The left and right operands are boolean expressions. If both the operands are non-zero, then the condition becomes true.
>
& (bitwise and operator) - The left and right operands are integral types. Binary AND Operator copies a bit to the result if it exists in both operands.
In your teacher's example a && b, the left operand 4 and the right operand 8 are both non-zero. So the condition will become true.
In your teacher's other example a & b, the left operand 4 or 0100 and the right operand 8 or 01000 copies no bits to the result. This is because there are no common set bits in either operand.
& is bitwise operator and, && is logical for example if you use two number and you want to use bitwise operator you can write & .
if you want to use to phrase and you want to treat them logically you can use && .
First this is the question I'm working on:
Evaluate each of the following expressions in C:
int x=1, y=7, z=0;
char a='m';
1) a ? y-x : x–y
2) x = 5 ? (y = z) : (z = y)
I understand the rest of the questions but number (1) confuses me... isn't it supposed to be a logical expression?
I mean 'm' cannot be true nor false; how can I answer this question? Is it simply "Error"? Or is there something I missed?
For number (2) the statement (z=y) should execute which changes z to 7, but isn't it supposed to be x == 5 and I tried it on a terminal and it changes both x and y to 0.
What am I missing?
In C ANY numeric type can be evaluated as a bool, and for such types, any non-zero value is 'true'. So since the character 'm' is non-zero (only '\0' is zero), it is "true"
Precedence -- All operators in C have precedence, and ?:, while lower than most, is higher than assignment operators. So this expression is equivalent to:
x = (5 ? (y = z) : (z = y))
I am learning bit algorithm and saw the equation that finds the max of two values:
r = x ^ ((x ^ y) & -(x < y)); // max(x, y)
The explanation says this equation will find the max without using comparison and "if x < y, then -(x < y) will be all ones". I cannot comprehend what the explanation means because I see a "less than" operator in the equation and if that is an less than operator, (x < y) should return only one bit of data. Therefore, for the explanation to make sense, the sign "<" cannot be the less than operator. I looked at the list of C operators and did not find other meanings for operator "<". Can someone tell me what does the operator "<" do in this equation? Thanks!
This is a very tricky code. The truth is that C does not have any Boolean type: it uses integer instead: 0 for false and 1 for true.
Therefore -(x<y) means
0 if x≥y
-1 if x<y
It is then used as a bit mask.
Edit
As suggested by Jonathan Leffler in comments, C has now a _Bool.
I made this small program to check what is it and how it is used:
#include <stdio.h>
int main() {
_Bool bFalse = 1>2;
printf("size of _Bool: %lu\nsize of comparison result: %lu\n", sizeof(bFalse), sizeof(1>2));
return 0;
}
This outputs:
size of _Bool: 1
size of comparison result: 4
In other words _Bool is one byte (a char), but it is not used as a result of Boolean comparisons (my compiler generates 4 bytes, that is, an int)
Note: tested with Clang on an Intel processor.
Edit: fix the types as kindly suggested in comments (and after checking the clang IR)
"if x < y, then -(x < y) will be all ones"
This is because, if x is less than y, condition evaluates to true (equal to 1). Notice the negetive sign before comparison, it makes the "1" of comparison result as "-1". In binary world, -1 has an all 1 representation, see Two's_complement. Example: 1111 1111 = -1.
However, if x > y, you get a -0 which is again all zero in binary.
Here, '<' is only a "x is_less_than y" comparison check, a logical operator.
using only bitwise operators (|, &, ~, ^, >>, <<), is it possible to replace the != below?
// ...
if(a != b){
// Some code
}
/// ...
this is mainly out of self interest, since I saw how to do it with == but not !=.
if(a ^ b) {
//some code
}
should work.
You can also use your preferred method for == and add ^ 0xFFFFFFFF behind it (with the right amount of Fs to match the length of the datatype). This negates the value (same as ! in front of it).
a != b means that there is at least one different bit in the bit representations of a and b. The XOR bit operator returns 1 if both input bit operands are different, 0 otherwise.
So, you can apply a XOR operation to a and b and check if the result is not equal to zero.
A bitwise version of the '!=' test could look something like:
if((a - b) | (b - a)) {
/* code... */
}
which ORs the two subtractions. If the two numbers are the same, the result will be 0. However, if they differ (aka, the '!=' operator) then the result will be 1.
Note: The above snippet will only work with integers (and those integers should probably be unsigned).
If you want to simulate the '==' operator, however, check out Fabian Giesen's answer in Replacing "==" with bitwise operators
x ^ y isn't always sufficient. Use !!(x ^ y). Values expecting a one bit return value will not work with x ^ y since it leaves a remainder that could be greater than just 1.
Yes, using this:
if (a ^ b) { }
"~" is equaled to NOT so that should work. example would be "a & ~b".
Using only bitwise operators (|, &, ~, ^, >>, <<) and other basic operators like +, -, and !, is it possible to replace the "==" below?
int equal(int x, int y) {
return x == y;
}
Remember that an XOR is the exactly same as NOT EQUALS and XNOR is exactly the same as EQUALS. So, the following will give you exactly what you want:
return !(x ^ y);
Two numbers are equal if there is no difference between them:
int equal(int x, int y){
return !(x-y);
}
The C ! operator is really just shorthand for != 0, so using it seems very close to cheating :)
Here's my take just using bitwise operations, assuming a 32-bit two's complement machine with arithmetic right shifts (technically, in C arithmetic right shifts are undefined, but every C compiler I've ever seen on a two's complement machine supports this correctly):
int t = (x - y) | (y - x); // <0 iff x != y, 0 otherwise
t >>= 31; // -1 iff x != y, 0 otherwise
return 1 + t; // 0 iff x != y, 1 otherwise
That said, actual compilers don't have this problem. Real hardware actually has direct support for comparisons. The details depend on the architecture, but there's two basic models:
Condition codes returned for arithmetic operations (e.g. x86 and ARM do this). In this case, there's usually a "compare" instruction which subtracts two values, doesn't write back to an integer register but sets the condition code/flags based on the result.
More RISC-like platforms typically have direct "branch if equal" and "branch if less than" operands that do a comparison and branch based on the result. It's basically equivalent to the C code
if (a == b) goto label;
or
if (a < b) goto label;
all in one machine instruction.
This example is the same as subtraction, but is more explicit as to how some architectures do register comparison (like the ARM, I believe).
return !(1 + ~x + y);
The 1 signifies the carry-bit input into the ALU. One number x is bitwise complemented. Taking the complement and adding 1 produces the two's complement of the number (x becomes -x), and then it's added to the other number to get the difference to determine equality.
So if both numbers are equal, you get -x + x => 0.
(On a register level the ! operator isn't done, and you just test the "zero bit" of the condition codes or flags register, which gets set if the register operation produces a result of zero, and is clear otherwise.)
As XOR is same as (!=), hence (x ^ y) will return 0 only for equal values.
My take is the following because it is sensible, uses bit-wise operator and working.
int notEqual(int x, int y){
return (x ^ y);
}
My Take on this
int equal(int x, int y){
if((x & ~y) == 0)
return 1;
else
return 0;
}
Explanation: If x == y, then x & ~y evaluates to 0 return 1, else return 0 as x!=y.
Edit1: The above is equivalent to
int equal(int x, int y){
return !(x & ~y) ; // returns 1 if equal , 0 otherwise.
}
The above code fails in certain cases where the Most significant bit turns to 1. The solution is to add a 1. i.e correct answer is
return !(x & (~y +1) );