I\'ve created a method to convert an int
to a bitfield (in a list) and it works, but I\'m sure there is more elegant solution- I\'ve just been staring at it for to
I'm doing this for my program where you specify a template to get your values from an int:
def field(template, value):
sums = [int(v) if v.__class__==str else len(bin(v))-2 for v in template]
return [(value>> (sum(sums[:i]) if i else 0) )&(~(~0<
how to use
in the template, specify ints relating to your bit-sizes:
field([0b1,0b111,0b1111], 204) #>>> [0, 6, 12]
or you can specify the bit-size of each value needed using strings: (noob friendly)
field(['1','3','4'], 204) #>>> [0, 6, 12]
EDIT: and vice versa: (separate code)
field(['1','3','4'], [0, 6, 12]) #>>> 204
field([0b1,0b111,0b1111], [0,3,9]) #>>> 150
the code:
def field(template, value):
res = 0
for t, v in zip(template, value)[::-1]: res = (res << (t.bit_length() if t.__class__ is int else int(t)) )|v
return res
EDIT2: faster code^