Python equivalent of C code from Twiddling Hacks bit?

I have a bit counting method that I am trying to do as quickly as possible. I want to try the algorithm below from Bit Twiddling Hacks , but I don’t know C. What is "type T" and what is the python equivalent (T) ~ (T) 0/3?

Generalization of the best bit counting method to integers of bit-width up to 128 (with type T parameters):

v = v - ((v >> 1) & (T)~(T)0/3);      // temp 
v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3);      // temp
v = (v + (v >> 4)) & (T)~(T)0/255*15;                      // temp
c = (T)(v * ((T)~(T)0/255)) >> (sizeof(v) - 1) * CHAR_BIT; // count
+3
source share
2 answers

T - , . C, , ( ) 8, 16, 32, 64 128. (T)~(T)0, , 2 ** N -1, N - T. , , N 8 .

Python, N, T .

def count_set_bits(v, N=128):
    mask = (1 << N) - 1

    v = v - ((v >> 1) & mask//3)
    v = (v & mask//15*3) + ((v >> 2) & mask//15*3)
    v = (v + (v >> 4)) & mask//255*15
    return (mask & v * (mask//255)) >> (N//8 - 1) * 8

:

(1) 2 ** 128. , .

(2) : , "//15" . C, , , , Python peephole .

(3) C Python. Python , , , Python. : !

+7

, , . , . .

(T) ~ (T) 0 " 1 , T". 4 , T-, .

>>> for N in (8, 16, 32, 64, 128):
...     all_ones = (1 << N) - 1
...     constants = ' '.join([hex(x) for x in [
...         all_ones // 3,
...         all_ones // 15 * 3,
...         all_ones // 255 * 15,
...         all_ones // 255,
...         ]])
...     print N, constants
...
8 0x55 0x33 0xf 0x1
16 0x5555 0x3333 0xf0f 0x101
32 0x55555555L 0x33333333L 0xf0f0f0fL 0x1010101L
64 0x5555555555555555L 0x3333333333333333L 0xf0f0f0f0f0f0f0fL 0x101010101010101L
128 0x55555555555555555555555555555555L 0x33333333333333333333333333333333L 0xf0f0f0f0f0f0f0f0f0f0f0f0f0f0f0fL 0x1010101010101010101010101010101L
>>>

, , 32- , 32- . : L 32- (Python 2.x) L Python 3.x.

, (T) ~ (T) 0 caper - . , k- 4 :

k bytes each 0x55
k bytes each 0x33
k bytes each 0x0f
k bytes each 0x01

- N-8 (.. 8 * (k-1)) . , , , CHAR_BIT 8, .

: , C Python. C . C 2 ** N. , N . . -. (a) Python int long (b) Python 2.X , Python 2.Xs int long Python 3.x int == Python 2.x long.

register &= all_ones Python. .

long int . , 32 long 0, 32- all_ones - long.

+2

Source: https://habr.com/ru/post/1732759/


All Articles