This story was originally published on Medium
Follow me:
Rust uses ! for the Bitwise Negation (Bitwise NOT). This produces different results depends on the type.
!
As you see !2 with the unsigned type returns 4294967293 and with the signed type returns -3.
!2
4294967293
-3
The bitwise negation on a signed integer returns the two’s complement as we saw previously in Rust signed two’s complement integer types.
The subtraction is the same as adding a negative number.
5 - 2 = 5 + (-2) = 3
This applies to binary as well.
0101 - 0010 = 0101 + (-0010) // (1) = 0101 + 1110 // (2) = 0011 // this is 3 in decimal number.
We find -0010 by finding the two’s complement of 0010 that is 1110.
-0010
0010
1110
The #1 tech hiring platform