0
int_val = 6074967776560871829
hex_val = []
for i in range(0,8):
    hex_val.append(hex(int_val % 256))
    int_val = int(int_val / 256)
print (hex_val)

output is :

['0x95', '0xf8', '0xda', '0x97', '0x1', '0x9f', '0x4e', '0x54']

but actually it should have been:

['0x95', '0xf9', '0xda', '0x97', '0x1', '0x9f', '0x4e', '0x54']

why is this difference? can anyone explain why and how to get the right result.

I am trying to send 64 bit integer through modbus using 8 byte

John Gordon
  • 29,573
  • 7
  • 33
  • 58
Nav
  • 11
  • 2

2 Answers2

3

The problem is here:

int_val = int(int_val / 256)

The result of the division is a float and there are known limitations, see the often mentioned thread: Is floating point math broken?

Use an integer division:

int_val = int_val // 256

or its short form //= or even better the divmod that gives you both results (quotient and remainder) and makes your program shorter and quicker. UPDATE: in reality it is not quicker, see the explanation here: Is divmod() faster than using the % and // operators? (thanks to Kelly Bundy for testing)

VPfB
  • 14,927
  • 6
  • 41
  • 75
  • Using `divmod`, even using a single-letter variable for the remainder, is six characters **longer** for me. And it's about 10% **slower**. What am I doing wrong? – Kelly Bundy Jun 09 '23 at 16:24
  • [my code](https://ato.pxeger.com/run?1=rVNBTsMwEJQ4-hV7QbFRaJOoJG2kvKSqUCA2tSBOlLhVUcVLuPQCd-6ceAAP4BU8gfXGoXDgRi6xd8czs7v243N7b9eNORyeNladzz9OPlXX1GB1LbUFXbdNZ_2OUaa3pdW91df9mK1laUKMV3LL2HVTyRgKCIKAaWMvt-Ud7tIomy3SLMvSizSaZ_E8WbC13PnscsVU04EGbaArzY3kUTgXOQP8PGpStq00FcctH2lPIblIhSDYGJtOCxdlTp68JP_oxXOEsENgpbd1U_HvmPPyl-MduiRHamOwb-iI2hSEwyJxGRR1a6dLqEGy7VCA30nDJXJyhxAiJKRgzM3F0e1VjsbBcahvggdWSUXj6rnyFViHXlo4g1imhLcO3-MYZcWJbqlWYpnH0WpFJzppNx0yBns3Zm57kaeTRD3A2wvsaeYUm1Hs_bUHX8vlsYFxFHn53waHGNlCV8MdG8pUWKLZ1FeyK_BwJGAK7n_Ee6Njj60YRNWPYkgihFt5X1APxM-Gjl0JQYnh4vv7P76DLw) – Kelly Bundy Jun 09 '23 at 16:27
  • @KellyBundy really conterintuitive, thanks for pointing that out – VPfB Jun 10 '23 at 17:54
0

I got the issue.
In python, int_val = int(int_val / 256) and int_val //= 256 are different, but I don't know why it is different. With int_val //= 256 it worked

kadamb
  • 1,532
  • 3
  • 29
  • 55
Nav
  • 11
  • 2
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 11 '23 at 22:56