Search code examples
pythonbit-fields

packing time into a bitfield


I need to pack the current time into a restrictive bitpattern.

the top 5bits is the hours, next 6 is minutes, next 6 seconds & the remainder are reserved

I came up with a nasty bitAND mask and then string concatenation before converting back to a 32bit integrer.

This seems overly convoluted & CPU expensive. Is there a more efficient & more to the point, elegant method?


Solution

  • How about:

    wl = 32
    hl = 5
    ml = 6
    sl = 6
    
    word = hours << (wl - hl) | minutes << (wl-hl-ml) | seconds << (wl-hl-ml-sl)