Quinn
Quinn

Reputation: 9404

Python get signed int from 32 bits

So I am reading 16 bit modbus registers to get a signed 32 int, currently I am doing this:

bits = (regs[0] << 16) + regs[1]

where regs is the array of registers which in pythons are handle as an int array

and it works for most cases, however when the number is negative then i get an underflow

For example a negative number may read as the registers being:

[65535, 65385]

which then is returned as

4294967145

Is there an easy way to fix this? Should I just be checking if the value is greater than INT32 MAX / 2 and if it is then subtract INT32 MAX? Or is there a better way?

The problem seems to be I am expecting a unsigned 32 bit int, but it should be a signed 32bit int

Upvotes: 0

Views: 1240

Answers (1)

Mark Ransom
Mark Ransom

Reputation: 308130

You can use the struct module to do a series of two conversions - first from unsigned 16-bit integers to bytes, then from bytes to signed 32-bit integer.

>>> regs = [65535, 65385]
>>> import struct
>>> b = struct.pack('>2H', *regs)
>>> b
b'\xff\xff\xffi'
>>> struct.unpack('>l', b)[0]
-151

Upvotes: 2

Related Questions