2

Is it possible to pack 4 chars into an int in python and have it be represented as one value in a bytearray? I'm looking into packing it into a struct, but run into an error if I try something like

characters = b'abcd' struct.pack('i',characters)

kvo
  • 23
  • 3
  • In reverse: [Convert a Python int into a big-endian string of bytes](http://stackoverflow.com/q/846038/4279) – jfs Feb 21 '16 at 08:43

1 Answers1

4

I'm not certain that I understand your problem -- If you want to take a bytestring and turn it into an integer, on python3.x, this is pretty easy:

import sys
value = int.from_bytes(b'abcd', sys.byteorder)  # for me, byteorder is `'little'`
assert value == 1684234849

On python2.x, you'd unpack the struct (which will work for python3.x too):

value, = struct.unpack('<i', b'abcd')
assert value == 1684234849

Now if you want to put this value into a bytearray -- The answer is no, you can't do that. bytearray only accepts values 0 -> 255

mgilson
  • 300,191
  • 65
  • 633
  • 696