简体   繁体   English

如何将十六进制ASCII字符串转换为有符号整数

[英]How can I convert a hex ASCII string to a signed integer

Input = 'FFFF' # 4 ASCII F's 输入='FFFF'#4 ASCII F'

desired result ... -1 as an integer 期望的结果... -1作为整数

code tried: 代码试过:

hexstring = 'FFFF'
result = (int(hexstring,16))
print result #65535

Result: 65535 结果:65535

Nothing that I have tried seems to recognized that a 'FFFF' is a representation of a negative number. 我所尝试过的任何事情似乎都没有认识到'FFFF'是负数的表示。

Python converts FFFF at 'face value', to decimal 65535 Python将'面值'处的FFFF转换为十进制65535

input = 'FFFF'
val = int(input,16) # is 65535

You want it interpreted as a 16-bit signed number. 您希望它被解释为16位有符号数。 The code below will take the lower 16 bits of any number, and 'sign-extend', ie interpret as a 16-bit signed value and deliver the corresponding integer 下面的代码将取任何数字的低16位,并且'sign-extend',即解释为16位有符号值并传递相应的整数

val16 = ((val+0x8000)&0xFFFF) - 0x8000

This is easily generalized 这很容易推广

def sxtn( x, bits ):
     h= 1<<(bits-1)
     m = (1<<bits)-1
     return ((x+h) & m)-h

In a language like C, 'FFFF' can be interpreted as either a signed (-1) or unsigned (65535) value. 在像C这样的语言中,'FFFF'可以解释为有符号(-1)或无符号(65535)值。 You can use Python's struct module to force the interpretation that you're wanting. 您可以使用Python的struct模块强制执行您想要的解释。

Note that there may be endianness issues that the code below makes no attempt to deal with, and it doesn't handle data that's more than 16-bits long, so you'll need to adapt if either of those cases are in effect for you. 请注意,可能存在以下代码未尝试处理的字节序问题,并且它不处理超过16位长的数据,因此如果这些情况中的任何一个对您有效,则需要进行调整。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM