The following code
printf("!%d = %d\n", 0, !0);
printf("!%d = %d\n", 1, !1);
printf("!%d = %d\n", -1, !-1);
gives
!0 = 1
!1 = 0
!-1 = 0
Now, considering that 0 = 0x00000000
, shouldn't !0 = 0xFFFFFFFF = -1
(for signed representation)? This messes up using int
/ long
in a bitfield and inverting everything at once.
What is the reason behind this? Is it only to avoid !1
to be considered as the boolean true
?
The reason is that in standard C, it has been specified that all operators returning a boolean return either 1 or 0. !0 calculates the logical not of 0, ie 1. The logical not of 1 would be then 0.
What you want to use is the bitwise NOT operator, ie ~0
which should be 0xFFFFFFFF == -1
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.