Let's say I have a list of numbers:
[1, 2, 5]
I need to generate a byte that represents the 5, 2 and 1 "position on". Which will result in the byte of value 19.
00010011
Is there an easy way to do this that doesn't involve me playing with an array of ones and zeros and them trying to convert it to a byte?
CodePudding user response:
Doing 2**(n-1)
will set a bit in the position you want:
print(bin(2**(1-1))) # 00001
print(bin(2**(2-1))) # 00010
print(bin(2**(5-1))) # 10000
This is equivalent to bit shifting:
1<<(1-1) # 00001
1<<(2-1) # 00001
1<<(5-1) # 10000
You can sum 2**(n-1)
for each number in your list:
nums = [1, 2, 5]
print(sum(2**(x-1) for x in nums))
Which results in the same result in applying the 'and' operation on each of the binary numbers:
00001
00010 AND
10000 AND
-----
10011
Which is equal to 19.
You can convert this to binary using the bin function:
print(bin(sum(2**(x-1) for x in nums)))
Output:
0b10011