Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert int to 16 bit unsigned short

Tags:

python

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)
like image 605
Milind Dumbare Avatar asked Nov 27 '14 13:11

Milind Dumbare


People also ask

How do I convert an int to unsigned?

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.)

What is a 16-bit unsigned integer?

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.

How do you convert int to short in Python?

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.

Is there an unsigned int in Python?

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.


1 Answers

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
like image 148
Ashwini Chaudhary Avatar answered Sep 22 '22 03:09

Ashwini Chaudhary