0

Say I have a bytearray like the following :
mask = bytearray([0b0001, 0b0100, 0b0111]),
where each bit represents a certain flag. I would like to add a flag to slices of the mask array like so :
mask[0:2] = mask[0:2] | 0b1000
but I get a TypeError :
TypeError: unsupported operand type(s) for |: 'bytearray' and 'int'
what would be the most elegant way of doing this?

Tried this, as well :
masks[0:2] = bytearray([bin(m | 0b0001) for m in masks[0:2]]) with error :
string must be of size 1

Thanks!

user5283407
  • 143
  • 8

1 Answers1

2

Can't be done directly without resorting to numpy, but you could work around it:

mask[:2] = (b | 0b1000 for b in mask[:2])

print(list(map(bin, mask)))

gets you:

['0b1001', '0b1100', '0b111']

You were close with your final attempt, but wrapping in bin was converting to a string representation, when you really wanted the original integer value.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • Thanks -- I didn't even think about numpy. I can do something like : `masks[0:2] = np.bitwise_or(masks[0:2], 0b0001)` and then see my changed flags with `map(np.binary_repr, masks)` – user5283407 Apr 03 '16 at 00:35