Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Word of Hexadecimal Value in Python

Tags:

python

hex

Crucial terminology aside, the word value of 0xFF20 is -224. From int( 'FF20', 16 ) I get 65312.

Considering the high-level nature of the language, what is the method for getting the "word" value of a hex string in Python?

like image 937
abestic9 Avatar asked Nov 23 '25 11:11

abestic9


2 Answers

If you want the signed value, like Pantashu mentioned, then you could use ctypes

ctypes.c_short(int('FF20', 16)).value
like image 113
Sajjan Singh Avatar answered Nov 25 '25 00:11

Sajjan Singh


If the first character has its high bit set (8-F), then subtract the value 0x1000... (number of 0s equal to the number of hexidecimal characters in the word) from your value after parsing it.

e.g. FF20 has its high bit set, convert it to decimal and subtract 0x10000 from it (65536 - 65312 = -224)

You can compute the value 0x100... by computing 2 to the power of 4*number of hexidecimal characters in word. e.g. 2^(4*4) = 65536

like image 23
Patashu Avatar answered Nov 25 '25 01:11

Patashu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!