Skip to content

Instantly share code, notes, and snippets.

@Noble-Mushtak
Created March 11, 2021 19:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Noble-Mushtak/f48f492f589f25fbef4f53c7de858913 to your computer and use it in GitHub Desktop.
Save Noble-Mushtak/f48f492f589f25fbef4f53c7de858913 to your computer and use it in GitHub Desktop.
def hexc2dec(bufp):
"""
Returns the decimal value of bufp[1:5],
where bufp[1:5] is the hexadecimal representation of a 16-bit number
in two's complement.
"""
# This variable accumulates our final answer
newval = 0
divvy = 4096
for pn in range(1,5):
# divvy is the power of 16 corresponding to the hex digit at index pn
# If pn=1, then divvy is 16^3
# If pn=2, then divvy is 16^2
# If pn=3, then divvy is 16^1
# If pn=4, then divvy is 16^0
# Get the ASCII code of this character
vally = ord(bufp[pn])
# 97 is ord("a"), so vally < 97 means that bufp[pn] is a normal digit
if vally < 97:
# Since ord("0")=48, ord("1")=49, ..., ord("8")=56, ord("9")=57
# the value of the hex digit bufp[pn] is ord(bufp[pn])-48
subby = 48
else:
# Since ord("a")=97, ord("b")=98, ..., ord("e")=101, ord("f")=102,
# the value of the hex digit bufp[pn] is ord(bufp[pn])-87
subby = 87
# Update newval with the value of bufp[pn] times divvy,
# which is the appropriate power of 16
newval += ( ord(bufp[pn]) - subby )*divvy
# Divide by 16 to update divvy for the next iteration of the loop
divvy /= 16
# Because this number is in two's complement,
# we need to subtract by 65536 (2^16)
# if the highest bit in the number is set.
# We check if the highest bit in the number is set by checking if newval
# is greater than 32767 (2^15-1).
if newval > 32767:
newval = newval - 65536
return newval
print(hexc2dec("?0000")) # 0
print(hexc2dec("?71ab")) # 29099
print(hexc2dec("?f100")) # -3840
print(hexc2dec("?ffff")) # -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment