How to convert signed to unsigned integer in python

后端 未结 7 1936
攒了一身酷
攒了一身酷 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 20:43

    python does not have any builtin to convert int to unsigned int.Instead it is having long for longer range.

    >>> val = 9223372036854775807 (maximum value of int 64)
    >>> type(val)
    
    >>> val += 1
    >>> type(val)
    
    

    By increasing the value of val by 1, I exceed the limit of a signed 64 bit integer and the value is converted to a long. If Python had used or converted to an unsigned integer, val would still have been an int. Or, not long.

    Signed integers are represented by a bit, usually the most significant bit, being set to 0 for positive numbers or 1 for negative numbers. What val & 0xff does is actually val & 0x000000ff (on a 32 bit machine). In other words, the signed bit is set to 0 and an unsigned value is emulated.

    An example:

    >>> val = -1
    >>> val & 0xff
    255
    

提交回复
热议问题