How to convert signed to unsigned integer in python

后端 未结 7 1883
攒了一身酷
攒了一身酷 2020-11-29 20:09

Let\'s say I have this number i = -6884376. How do I refer to it as to an unsigned variable? Something like (unsigned long)i in C.

相关标签:
7条回答
  • 2020-11-29 21:02

    You could use the struct Python built-in library:

    Encode:

    import struct
    
    i = -6884376
    print('{0:b}'.format(i))
    
    packed = struct.pack('>l', i)  # Packing a long number.
    unpacked = struct.unpack('>L', packed)[0]  # Unpacking a packed long number to unsigned long
    print(unpacked)
    print('{0:b}'.format(unpacked))
    

    Out:

    -11010010000110000011000
    4288082920
    11111111100101101111001111101000
    

    Decode:

    dec_pack = struct.pack('>L', unpacked)  # Packing an unsigned long number.
    dec_unpack = struct.unpack('>l', dec_pack)[0]  # Unpacking a packed unsigned long number to long (revert action).
    print(dec_unpack)
    

    Out:

    -6884376
    

    [NOTE]:

    • > is BigEndian operation.
    • l is long.
    • L is unsigned long.
    • In amd64 architecture int and long are 32bit, So you could use i and I instead of l and L respectively.
    0 讨论(0)
提交回复
热议问题