1

Is there a byte type in Python3? I only know there is a bytearray.

What I want is that, there is a byte 0x01, then do the Complement Operator ~ the result will be 0xFE, however when I do the following steps, the result is -2 and -2 can't be added to the bytearray.

>>> data=bytearray([0x01])
>>> data
bytearray(b'\x01')
>>> ~data[0]
-2
>>> data[0]=~data[0]
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
ValueError: byte must be in range(0, 256)
halex
  • 16,253
  • 5
  • 58
  • 67
xuanzhui
  • 1,300
  • 4
  • 12
  • 30

2 Answers2

2

Python 3 has 2 types dealing with bytes : the bytes type, which is not mutable (analogous to str) and the bytearray with is mutable. If you need to cast an integer to a byte, you simply take the 8 lower order bits with & 0xFF.

So your last line should be :

data[0] = ~ data[0] & 0xFF
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • just to emphasis, for Python 3, bitwise operators work on "int" type, not "bytes". So `a = b'\x7f'; a & 0xff` won't work, instead it should be `a=b'\x7f'[0]; a & 0xff` – Zhe Hu Nov 14 '16 at 20:58
0

You can take ~data[0] modulo 256 to get a correctly shifted value:

>>> data = bytearray([0x01])
>>> data[0] = ~data[0]%256
>>> data
bytearray(b'\xfe')

See negative numbers modulo in python for more information on modulo operation on a negative number.

halex
  • 16,253
  • 5
  • 58
  • 67
  • And why not simply `~data[0] & 0xFF` ? It keeps the 8 lower order bits with no problem of negative modulo ... – Serge Ballesta Feb 06 '15 at 09:10
  • @SergeBallesta Modulo of a negative number is well defined so why not? It's the same as `&0xFF`so nothing speaks against it :) – halex Feb 06 '15 at 10:09