0

I have different uint64 numbers which I want to send via CAN-Bus with SocketCAN in Python. I need to divide the large number in 8 bytes, so I can assign the values to the CAN data-bytes. But I'm struggling with the implementation. I am grateful for any help or suggestion.

Thanks for your help!

StealthScream
  • 43
  • 1
  • 5

2 Answers2

1

When it comes to convert numbers to their byte representation, the struct module is your friend:

i = 65357
print(hex(i))
bigendian = struct.pack(">Q", i)
littleendian = struct.pack("<Q", i)

print(repr(bigendian)
print(repr(littleendian)

output is as expected:

'0x10001'
b'\x00\x00\x00\x00\x00\x01\x00\x01'
b'\x01\x00\x01\x00\x00\x00\x00\x00'

That means that you can easily use the individual bytes (in the order you need) to send them via CAN-bus

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
1

Assuming you are using Python 3 you can simply use Python int's to_bytes method like so:

i = 65357
print(hex(i))
print(i.to_bytes(8, 'big'))
print(i.to_bytes(8, 'little'))

Output:

0xff4d
b'\x00\x00\x00\x00\x00\x00\xffM'
b'M\xff\x00\x00\x00\x00\x00\x00'

Not sure if you're using the python-can library, but if you are you can pass either bytes, a list of ints or a bytesarray to the can.Message.

Hardbyte
  • 1,467
  • 13
  • 25