HEX_BITS = 4
def shift_left1( bits ):
#Left shift adding 1 instead of 0
mask = 0
for i in range( bits ):
mask = (mask << 1) + 1
return mask
def hex_signal( value, bits ):
# Retuns the mask with bit signal
signal_mask = 1 << bits
return -( value & ( signal_mask ) )
def hex_without_signal( value, bits ):
# Returns value with the number of bits given (from less significant to most)
return value & shift_left1( bits )
def hex2dec( hstring, signed=True ):
value = int( hstring, 16)
if signed: #Do we want to check the signal?
value_bits = len( hstring ) * HEX_BITS # A full hex digit have four bits
shift_times = value_bits - 1 # Times to subfunctions shifts
signal_mask = hex_signal( value, shift_times ) # Mask with bit value setted
unsigned_hex_mask = hex_without_signal( value, shift_times ) # Value without most significant bit
return signal_mask | unsigned_hex_mask # Or bit a bit from the unsigned value and signal mask
else: # If not just returns the native conversion
return value
经过几个小时的研究,我找到了一个解决办法。你知道吗
它将每一个十六进制数字作为一个4位整数来计算,虽然这并不总是正确的,但也不会是一个问题。你知道吗
例如:0x7是0b111。因此,Python中的整数将有3位。核对:
但是如果最高有效位(信号位)没有第四位,它将被计算为0,这正是我们在这种情况下想要的。你知道吗
因此,代码(未优化)但我能给出的最清晰的代码是:
示例:
相关问题 更多 >
编程相关推荐