Search code examples
pythonstruct

U8,U16,U32 representation in python


I have two questions and they both are inter-related.

My first question is: As for example, I have to declare few U8 variables, U16 and U48 and then have to pass the values to them. After passing the values, I have to covert them into a binary (one binary-all of them combined). I don't know how to perform this task How to define U8, U16 and U32 in python(in binary). I know struct as a module. But when I write

ex=binascii.hexlify(struct.pack("I",1))

it returns b'01000000' instead of returning 01000000. Is there any other way to do it(I need it in U8 format)

My second question is:

How can disintegrate U8 into 2MSbits and 6LSbits


Solution

  • I have to declare few U8 variables, U16 and U48 and then have to pass the values to them.

    Python is a dynamic-typed language to a variable doesn't have a fixed type, the type of your value will depend on the value it holds. That said, in python there is a single integer type (int), and it can hold any signed integer number, if your number is to big it will be automatically converted to a bigint.

    E.g.

    var1 = 256  # A plain integer
    var2 = 4294967296L # Bigger than 2**31, it has to be suffixed with an L
    

    Since there is a single integer type, if you want to limit your variable to hold a given binary width, you should mask the LSBits.

    E.g.

    bignum = 2**50 - 1
    only_8_lsb = bignum & 0xFF
    only_16_lsb = bignum & 0xFFFF
    only_48_lsb = bignum & (2**49 - 1)
    

    After passing the values, I have to covert them into a binary (one binary-all of them combined).

    Technically, the numbers are already stored as binary. If you want to show the binary representation of a number, you'll have to hold it in a string, and you can use formatting

    E.g. Converting a number to a zero-paded 8-digits binary representation

    > "{0:08b}".format(0b11000011)
    '11000011'
    

    E.g. Converting a number to a zero-paded 16-digits binary representation

    > "{0:016b}".format(0xCAFE)
    '1100101011111110'
    

    Hopefully, you noticed that a you can specify an integer in different ways.

    How can disintegrate U8 into 2MSbits and 6LSbits

    Unless you need other representation, use bit operators as noted in the other answer.

    struct has other purpose, it allows you to convert some python values to a string of bytes, as would other languages will see them in memory. And you are getting a b prefixed string, because in Python 3 str is meant to store unicode code points while bytes are meant to store raw bytes (sequences of "numbers" in the range 0 <= chr > 256).