输入 = 'FFFF' # 4个ASCII码为F的字符
期望结果 ... 以整数形式返回-1
尝试的代码:
hexstring = 'FFFF'
result = (int(hexstring,16))
print result #65535
结果:65535
我尝试的所有方法都似乎没有将“FFFF”识别为负数的表示形式。
Python将FFFF“按面值”转换为十进制数字65535
input = 'FFFF'
val = int(input,16) # is 65535
您希望将其解释为16位有符号数字。 下面的代码将获取任何数字的低16位,并进行“符号扩展”,即将其解释为16位有符号值并输出相应的整数。
val16 = ((val+0x8000)&0xFFFF) - 0x8000
这很容易推广应用
def sxtn( x, bits ):
h= 1<<(bits-1)
m = (1<<bits)-1
return ((x+h) & m)-h
import struct
input = 'FFFF'
# first, convert to an integer. Python's going to treat it as an unsigned value.
unsignedVal = int(input, 16)
assert(65535 == unsignedVal)
# pack that value into a format that the struct module can work with, as an
# unsigned short integer
packed = struct.pack('H', unsignedVal)
assert('\xff\xff' == packed)
# ..then UNpack it as a signed short integer
signedVal = struct.unpack('h', packed)[0]
assert(-1 == signedVal)
if(value > 0x7FFF) value -= 0x10000
? - John Dvorak