0

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?

Naib
  • 999
  • 7
  • 20
  • Why would you need a string to perform bit operations? – JohanL May 07 '17 at 20:16
  • https://docs.python.org/3/library/struct.html and http://stackoverflow.com/questions/142812/does-python-have-a-bitfield-type – handle May 07 '17 at 20:17
  • @JohanL well... my 1st pass was via the bin(x) method which returns strings, thus slicing multiple of these causes alot of string. The multiple bitshift (as your answer shows) was my fallback but I was hoping for something closer to a union in Python. – Naib May 09 '17 at 08:31
  • @handle I actually came across another site advocating ctypes just after I posted. Your comment helped clarify aspects of it – Naib May 09 '17 at 08:31

2 Answers2

0

How about:

wl = 32
hl = 5
ml = 6
sl = 6

word = hours << (wl - hl) | minutes << (wl-hl-ml) | seconds << (wl-hl-ml-sl)
JohanL
  • 6,671
  • 1
  • 12
  • 26
0

Between additional searches ( http://varx.org/wordpress/2016/02/03/bit-fields-in-python/ ) and a comment I settled on:

class TimeBits(ctypes.LittleEndianStructure):
    _fields_ = [
            ("padding", ctypes.c_uint32,15), # 6bits out of 32
            ("seconds", ctypes.c_uint32,6), # 6bits out of 32
            ("minutes", ctypes.c_uint32,6), # 6bits out of 32
            ("hours", ctypes.c_uint32,5), # 5bits out of 32
            ]

class PacketTime(ctypes.Union):
    _fields_ = [("bits", TimeBits),
            ("binary_data",ctypes.c_uint32)
            ]


packtime = PacketTime()
now = datetime.today().timetuple()
packtime.bits.hours = now[3]
packtime.bits.minutes = now[4]
packtime.bits.seconds = now[5]

It offers a cleaner structured setting of the associated fields, especially as this is called at least every second. A similar structure has been created for Date and other bitpacking vectors

Naib
  • 999
  • 7
  • 20