0
C Language
#include <stdio.h> int main() { int y = 0; int x = (~y == 1); printf("%d", x); return 0; }
5 Respostas
+ 4
~ is the bitwise inversion operator, it works by inverting each bit in a number, when a bit value is 0, it is inverted to 1, vice versa.
<y> value is zero, ~y yields -1, when you compare value of ~y and 1 it evaluates to false (zero), because they're not equal. Then store the comparison result (which is false, or zero) in <x>, this means <x> value is now zero, then you print value of <x>, I guess that's what happened : )
Hth, cmiiw
+ 4
Simple yet to the point explanation, Ipang . ;)
Also, I want to emphasize the importance of keeping an eye on the signedness of the variable before performing bit-level operations. Because in a specific bit field each signed and unsigned version of the same variable lead to different interpretation by the machine , for example
int x = 0;
Binary form (32bit) of the x:
0000 0000 0000 0000 0000 0000 0000 0000
comprises one signed bit (bit 31st) and thirty one magnitude bits (bit 0 to 30)
unsigned int y = 0;
With the same binary form as the x but comprises thirty two magnitude bits (all bits)
So, making a one's complement like ~x or ~y just flips the bits on-the-fly during comparison as
1111 1111 1111 1111 1111 1111 1111 1111
but depends on being signedness, it will be interpreted to -1(for x in two's complement) or 4294967295 (for y)
_____
Further readings:
1. https://en.m.wikipedia.org/wiki/Ones'_complement
2. http://sandbox.mc.edu/~bennet/cs110/tc/tctod.html
+ 4
Thanks Ipang for encouraging comments. Yeah, specifically when doing arithmetic shift right operation you almost always want to make sure that the integral type is unsigned since the sign bit will repopulate its value and feed it to bit field from left.
_____
https://en.m.wikipedia.org/wiki/Arithmetic_shift
http://www.c-jump.com/CIS77/ASM/Flags/F77_0160_sar_instruction.htm
+ 1
C++ Soldier (Babak)
Thanks and yes that's true, I was once also so confused of the use of the sign bit, that I had a hard time trying to write myself a decimal → binary converter for negative values, thankfully we have helpful friends in this community, that I now understand it a bit better : )
+ 1
C++ Soldier (Babak)
One nice tips that is, I'll keep that in my notes book, didn't do much bit shifting operations yet, might make a good practice for me : )