What does this code mean?
int possible = 1;
for (int i = 0; i < n - 1; ++i){
possible += (n_size[i] ^ n_size[i + 1]) < 0;
}
I think this is ^
XOR, but how is it working in this code? That's strange,
Because I thought when we use XOR we have just 0 or 1. Please, help me to understand.
Let's see this line :
possible += (n_size[i] ^ n_size[i + 1]) < 0;
We don't know about n_size
but I'll suppose it is an array of n
int
. So we XOR (bitwise) two consecutive terms of n_size
, and determine the sign of the result (by comparing it to 0).
Bitwise-XOR is operating bit per bit, so ( ABCD = 1011 ^ 0101
<=> A = 1 ^ 0
, B = 0 ^ 1
, C = 1 ^ 0
, D = 1 ^ 1
).
int
are encoded in a certain manner, which allows us to get the sign with the most-significant bit (in the number 0bX???????
, if X=1 the number is negative, else the number is positive).
So (A ^ B) < 0
is equivalent to (A < 0) ^ (B < 0)
.
So this line increments possible
when two consecutive terms have not the same sign.
Finally, possible
counts the number of consecutive terms alterning their sign.
PS : notice that float
and double
have their sign determined by their most-significant-bit too, so it works the same if n_size
is an array of float
or double
.
As coderedoc was a little short in his comment: ^
is a bit-wise operator, just as |
and &
, too. Those operators are applied on every pair of corresponding bits (and for such a pair, XOR as you understood it) within two variables:
unsigned char c1 = 0b11001010;
unsigned char c2 = 0b10101100;
unsigned char c3 = c1 ^ c2; // == 0b01100110
unsigned char c4 = c1 & c2; // == 0b11101110
unsigned char c5 = c1 | c2; // == 0b10001000
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.