python字符串和數值之間轉換,進制轉換等
1:int函數將16進制字符串轉化爲10進制整數
a = “0x12”
int(a, 16)#18
int(a, 10)#error
a = “12”
int(a, 16)#18
int(a, 10)#12
2:16進制字符串轉換爲有符號整數 參考鏈接
def twos_complement(hexstr,bits):
value = int(hexstr,16)
if value & (1 << (bits-1)):
value -= 1 << bits
return value
twos_complement('FFFE',16)
-2
twos_complement('7FFF',16)
32767
twos_complement('7F',8)
127
twos_complement('FF',8)
-1
3:負數轉換爲16進制字符串參考鏈接
def tohex(val, nbits):
return hex((val + (1 << nbits)) % (1 << nbits))
print tohex(-199703103, 64)#0xfffffffff418c5c1L
print tohex(199703103, 64) #0xbe73a3fL