python - Bitwise operation and usage -
consider code:
x = 1 # 0001 x << 2 # shift left 2 bits: 0100 # result: 4 x | 2 # bitwise or: 0011 # result: 3 x & 1 # bitwise and: 0001 # result: 1 i can understand arithmetic operators in python (and other languages), never understood 'bitwise' operators quite well. in above example (from python book), understand left-shift not other two.
also, bitwise operators used for? i'd appreciate examples.
bitwise operators operators work on multi-bit values, conceptually 1 bit @ time.
and1 if both of inputs 1, otherwise it's 0.or1 if one or both of inputs 1, otherwise it's 0.xor1 if exactly one of inputs 1, otherwise it's 0.not1 if input 0, otherwise it's 0.
these can best shown truth tables. input possibilities on top , left, resultant bit 1 of 4 (two in case of not since has 1 input) values shown @ intersection of inputs.
and | 0 1 or | 0 1 xor | 0 1 not | 0 1 ----+----- ---+---- ----+---- ----+---- 0 | 0 0 0 | 0 1 0 | 0 1 | 1 0 1 | 0 1 1 | 1 1 1 | 1 0 one example if want lower 4 bits of integer, , 15 (binary 1111) so:
201: 1100 1001 , 15: 0000 1111 ------------------ 9 0000 1001 the 0 bits in 15 in case act filter, forcing bits in result 0 well.
in addition, >> , << included bitwise operators, , "shift" value respectively right , left number of bits, throwing away bits roll of end you're shifting towards, , feeding in 0 bits @ other end.
so, example:
1001 0101 >> 2 gives 0010 0101 1111 1111 << 4 gives 1111 0000 note left shift in python unusual in it's not using fixed width bits discarded - while many languages use fixed width based on data type, python expands width cater bits. in order discarding behaviour in python, can follow left shift bitwise and such in 8-bit value shifting left 4 bits:
bits8 = (bits8 << 4) & 255 with in mind, example of bitwise operators if have 2 4-bit values want pack 8-bit one, can use 3 of operators (left-shift, and , or):
packed_val = ((val1 & 15) << 4) | (val2 & 15) - the
& 15operation make sure both values have lower 4 bits. - the
<< 44-bit shift left moveval1top 4 bits of 8-bit value. - the
|combines these 2 together.
if val1 7 , val2 4:
val1 val2 ==== ==== & 15 (and) xxxx-0111 xxxx-0100 & 15 << 4 (left) 0111-0000 | | | +-------+-------+ | | (or) 0111-0100
Comments
Post a Comment