bit-manipulation

bit-wise operation unary ~ (invert)

bit-wise operation unary ~ (invert) Question: I’m a little confused by the ~ operator. Code goes below: a = 1 ~a #-2 b = 15 ~b #-16 How does ~ do work? I thought, ~a would be something like: 0001 = a 1110 = ~a why not? Asked By: Alcott || Source Answers: You are …

Total answers: 5

Bitwise operation and usage

Bitwise operation and usage Question: Consider this 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 the arithmetic operators in Python (and other …

Total answers: 18

what is the correct way to process 4 bits inside an octet in python

what is the correct way to process 4 bits inside an octet in python Question: I’m writing an application to parse certain network packets. A packet field contains the protocol version number in an octet, so that 4 high bits are the ‘major’ and low 4 are the ‘minor’ version. Currently I am parsing them …

Total answers: 4

Is & faster than % when checking for odd numbers?

Is & faster than % when checking for odd numbers? Question: To check for odd and even integer, is the lowest bit checking more efficient than using the modulo? >>> def isodd(num): return num & 1 and True or False >>> isodd(10) False >>> isodd(9) True Asked By: riza || Source Answers: Yep. The timeit …

Total answers: 9