Search code examples
pythonbitmapbinarybitbit-shift

Last two digits of decimal number with a mask?


To get the last N digits of a decimal number I usually convert it to a string. For example, for two digits:

n = 129387
int((str(n)[-2:]))
# 87

With binary its relatively straightforward to do this with a mask, such as:

n = 0b00101001
'{:02b}'.format(0b00101001& 0b11)
# '01'
# -- or -- 
'{:02b}'.format(0b00101001& 0x3)
# '01'

Is it possible to apply a mask to a deicimal number to get the last two digits, 87 in the above example?


Solution

  • You are referring to the mod operator, e.g.:

    In []:
    129387 % 100  # 10**2
    
    Out[]:
    87
    

    The general case is base**n where n is the number of digits in the base, e.g. binary case:

    In []:
    format(0b00101001 % 2**2, '02b')
    
    Out[]:
    '01'
    
    In []:
    format(0b00101001 % 2**4, '02b')
    
    Out[]:
    '1001'