I want to trim an integer to 16 bit word (unsigned short) in Python. Something like following does not work
word = array("H")
word.insert(0,0x19c6acc6)
You can convert an int to an unsigned int . The conversion is valid and well-defined. Since the value is negative, UINT_MAX + 1 is added to it so that the value is a valid unsigned quantity. (Technically, 2N is added to it, where N is the number of bits used to represent the unsigned type.)
Integer, 16 Bit Unsigned: Unsigned whole or natural numbers ranging from 0 to +65535. Integer, 16 bit Unsigned data type is used for numerical tags where only positive variables will be used.
Python str() function (typecasting) is used to create a string version of the object (any Python data type) passed as an argument to it. The return value of the str() function is the string representation of the object. Therefore, the str() function can be used to convert an integer into a string.
Python contains built-in numeric data types as int(integers), float, and complex. Compared to C programming, Python does not have signed and unsigned integers as data types.
Use ctypes.c_ushort
:
>>> import ctypes
>>> word.insert(0, ctypes.c_ushort(0x19c6acc6).value)
>>> word
array('H', [44230])
If NumPy is available then:
>>> numpy.ushort(0x19c6acc6)
44230
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With