[PYTHON] Bit mask

Python --Initial version

bitmask.py


# b5-Get the mask of b3. 
startbit=3   #startbit b3
bitlen=3     #Bit length of 3 bits including start bit(b5b4b3)
b=0
for i in range(startbit, startbit + bitlen):
     b|=1<<i

bin(b) #=> '0b111000'

# b10-Get the mask of b0. 
startbit=0 #startbit b0
bitlen=11 #Bit length of 11 bits including start bit(b10...b1b0)
b=0
for i in range(startbit, startbit + bitlen):
    b|=1<<i

bin(b) # '0b11111111111'

# b49-Get 45 masks.
startbit=45 #startbit b45
bitlen=5 #Bit length of 5 bits including start bit(b49b48b47b46b45)
b=0
for i in range(startbit, startbit + bitlen):
    b|=1<<i

bin(b) #=> '0b11111000000000000000000000000000000000000000000000'

Python --shiracamus version

bitmask.py


def bitmask(startbit, bitlen):
     return ((1 << bitlen) - 1) << startbit

If you embody it with startbit = 3 and bitlen = 3, you can see that the mask is required with a complement feeling. 1 << bitlen :  1 <<3 = 0b1000

(1 << bitlen) - 1 :  (1 << 3) - 1 = 0b1000 - 1 = 0b111

(1 << bitlen) - 1) << starbit :  ((1 << 3) - 1) << 3 = 0b111 << 3 = 0b111000

C-Initial version

http://melpon.org/wandbox/permlink/KAdTUEdphWrNncP0

bitmask.c


#include <stdio.h>
unsigned long long bitmask1(
    unsigned char startbit,
    unsigned char bitlen
){
    return (((unsigned long long)0x1 << bitlen)-0x1) << startbit;
}

C-shiracamus version

bitmask2.c


unsigned long long bitmask2(
    unsigned char startbit,
    unsigned char bitlen
){
    if (startbit >= 64) return 0;
    if (bitlen >= 64) return ~0ULL << startbit;
    return ((1ULL << bitlen) - 1ULL) << startbit;
}

C-Third Edition

As a result of various thoughts, it became less interesting.

Execution result comparison http://melpon.org/wandbox/permlink/hTrTCCmfgjORuGsT

bitmask3.c


 unsigned long long bitmask3(
    unsigned char startbit,
    unsigned char bitlen
){
    unsigned long long bm = 0x0UL;
    if (bitlen == 64u){
        bm = ~(0x0ULL);
    } else {
        bitlen %= 64u;
        bm = (0x1ULL << bitlen) - 0x1ULL ;
    }
    startbit %= 64u;
    bm <<= startbit;
    
    return bm ;
}

Recommended Posts

Bit mask
Bit operation
Logical operation / bit operation 0
PYTHON2.7 64bit version