Nå har jeg tullet meg borti noe som kalles bitwise operators som jeg ikke skjønner skjønner så mye av.
Det gjelder følgende tegn: <<, >>, &, |, ~, ^.
Jeg fant en forklaring på det, men får det ikke til å stemme helt når jeg tester i Python.
- x << y
Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.
- x >> y
Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**y.
- x & y
Does a "bitwise and". Each bit of the output is 1 if the corresponding bit of x AND of y is 1, otherwise it's 0.
- x | y
Does a "bitwise or". Each bit of the output is 0 if the corresponding bit of x AND of y is 0, otherwise it's 1.
- ~ x
Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1. This is the same as -x - 1.
- x ^ y
Does a "bitwise exclusive or". Each bit of the output is the same as the corresponding bit in x if that bit in y is 0, and it's the complement of the bit in x if that bit in y is 1.
Si at x = 5 og y = 7.
1) Den første er grei. Da vil x<<y = 5 * 2^7= 640.
2 ) Den andre er litt rar, men gjetter at det har med integerdivisjon å gjøre, så derfor får jeg ikke noe spesielt vettugt ut når jeg prøver x>>y = 5/(2^7) = 5/128. Blir bare 0, men det gir mening hvis man ikke regner med tatt mellom 0 og 1.
3) Hæ?
Kode
2&2
Out[69]: 2
2&3
Out[70]: 2
2&4
Out[71]: 0
2&5
Out[72]: 0
2&6
Out[73]: 2
4) Hæ?
Kode
2|2
Out[74]: 2
2|3
Out[75]: 3
2|4
Out[76]: 6
2|5
Out[77]: 7
2|6
Out[78]: 6
5) Denne er også grei. ~x = -5-1 = -6
6) Hæ?
Kode
2^2
Out[81]: 0
2^3
Out[82]: 1
2^4
Out[83]: 6
2^5
Out[84]: 7
2^6
Out[85]: 4
Så nummer 1, 2 og 5 er "greie". Skjønner likevel ikke når det skal være aktuelt å bruke de.
Grunnen til at jeg kom inn på dette var at jeg fikk se en kode med to lister (a og b) etterfulgt av set(a) | set(b), hvor set skal plukke ut unike verdier av en liste i uordnet rekkefølge.