-1

im pulling data from a modbusTCP server, but when i should receive a negative value it shows as a big number.

self.export = self.c.read_holding_registers(37113, 2)[1]

I know it has something to do with it being signed or unsigned but im really having trouble solving it.

    print("export:      " + "{:02f}W".format(self.inverter.export))
    print("exportBytes: " + "{:16b}W".format(self.inverter.export))
    print("export:      " + "{:02f}W".format(self.inverter.export))
    print("export 1:    " + "{:16b}W".format(1))
    print("export-1:    " + "{:16b}W".format(-1))

Prints out

export:      59142.000000kW
exportBytes: 1110011100000110kW
export:      59142.000000kW
export 1:                   1kW
export-1:                  -1kW

Any guesses?

Mads Gadeberg
  • 1,429
  • 3
  • 20
  • 30

2 Answers2

0

The bytes received is implicitley cast to an unsigned int.

To convert to a signed int we

  1. use the Int.to_bytes() to get the bytes and
  2. use the int.from_bytes() to get the signet int.
varBytes = theInteger.to_bytes(2, 'big')                               # getting raw bytes
signedInt = int.from_bytes(varBytes , byteorder='big', signed = True)  # getting signet int vale

copied to an int as being unsigned.The "int" that is received is implicitley cast to an int by python.

Mads Gadeberg
  • 1,429
  • 3
  • 20
  • 30
0

Mads' solution I think will work, but this is maybe more illustrative of what's going on:

def int16_decode(uint16_val):
    if uint16_val > 0x8000:
        uint16_val -= 0x10000
    return uint16_val

It's how signed ints are stored in memory. int16 is like uint16 except the most-significant-bit is reserved as the sign bit. So if you read a negative int16 as a uint16, it will be very big since most significant bit of 16 is 1.

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 28 '22 at 22:53