0

I have a 4 bytes value that need to be applied a masking

x = b'\x22\x22\x22\x22'
mask = b'\xff\xff\x00\x00'

I tried x & mask but show unsupported operand type(s) error.

TypeError: unsupported operand type(s) for &: 'bytes' and 'bytes'

Please advice how I can apply the masking here?

Best

J_yang
  • 2,672
  • 8
  • 32
  • 61

1 Answers1

1
 b"".join([bytes([a & b]) for a,b in zip(x,mask)])

result:

b'""\x00\x00'
Or Y
  • 2,088
  • 3
  • 16
  • @Tomerikoo Well, `"` in ascii is 34 in decimal which is 0x22 in hex, I just copied the output from IPython – Or Y Sep 23 '20 at 14:17
  • Yeah, that is correct. But actually I need to convert it back to short int. Maybe just a memoryview()? can you advice? Basically masking masking, I wish to take the first 2 as a uint val_1 and the last 2 as a uint val_2 – J_yang Sep 23 '20 at 14:19
  • @J_yang you can use ```int.from_bytes``` for that - for example: ```int.from_bytes(b'\xff\xff', byteorder='big')``` you can split the ```bytes``` every two bytes in a list for that – Or Y Sep 23 '20 at 14:25