+ 1

Output explain

#include<stdio.h> int main() { if(7&8) printf("Honesty"); if(~7&0x000f==8)) printf("is the best policy \n"); }

4th Mar 2022, 7:41 AM
Abhishek
Abhishek - avatar
7 Answers
+ 5
During computation, mathematical operations like: addition, subtraction, multiplication, division, etc are converted to bit-level which makes processing faster and saves power. Bitwise operators are used in C programming to perform bit-level operations & ==> Bitwise AND ----------------------- The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If either bit of an operand is 0, the result of corresponding bit is evaluated to 0. Let us suppose the bitwise AND operation of two integers 7 and 8: 7 =0111 (in binary) 8 =1000 (in binary) 7&8=0000(in binary) = 0(in decimal) Result if(7&8) is false .
4th Mar 2022, 8:27 AM
Tarik Khalil
Tarik Khalil - avatar
+ 4
You need to study bitwise operations and bit masks. They are ubiquitous in C programming. Essentially, 7 sets the bit 0, 1, and 2. 8 set the bit 3. An AND operation filters the common set bits - which in this case are none. And no set bits is the value 0, and 0 is intepreted as false in a boolean context. To sum up 7&8 is 'false' (thanks to C's weak typing). ~7 is a bit inversion of 7, setting all bits to1 except bits 0, 1, and 2, which were 1 and are set to zero. Hexadecimal 0xF are the bits 0, 1, 2, and 3 set to 1. The common set bits of ~7 and 0xF is the bit number 3. And the 3rd bit 1 all others zero is the integer value 8 (2 to the power of 3). Thus that condition evaluates to true.
4th Mar 2022, 8:29 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 3
output : is the best policy
4th Mar 2022, 8:15 AM
Tarik Khalil
Tarik Khalil - avatar
+ 3
4th Mar 2022, 8:16 AM
Rishi
Rishi - avatar
+ 3
Tarik Khalil wow great explanation🙌đŸ˜Č
4th Mar 2022, 12:06 PM
Rishi
Rishi - avatar
+ 2
Bitwise compliment operator is an unary operator (works on only one operand). It changes 1 to 0 and 0 to 1. It is denoted by ~. ~ ==> Bitwise complement -------------------------------- 7 =0111 (in binary) ~7 =1000 (in binary) = 8 (in decimal) 0x000f (in hexadecimal) = 1111 (in binary) = 15 (in decimal) ~7&0x000f (Bitwise AND) = 1000 (in binary) = 8 (in decimal) Result if(~7&0x000f==8) is true . ---------------------------------------- output : is the best policy
4th Mar 2022, 8:35 AM
Tarik Khalil
Tarik Khalil - avatar