2

How can I convert number to 4 bytes little endian with python?

For example : 1 -> 01000000 and 258 -> 02010000

1
  • 1
    do you have any code example? or do you expect someone code it for you? please check How to Ask Commented Jul 1, 2020 at 21:12

1 Answer 1

4

Try with struct, 'this module performs conversions between Python values and C structs represented as Python strings':

import struct
print(struct.pack('<i', 258))

where < mean little-endian and i that the element to be pack is an integer

Output:

b'\x02\x01\x00\x00'
Sign up to request clarification or add additional context in comments.

2 Comments

But if this code will run at 64 bits machine this will be 8 bytes. Is there any way to limit that explicit to 4 byte?
The code is running in a 64 bits machine and the result is as shown, if you want to know more about it please refer to: docs.python.org/2/library/struct.html @ttx32063Eoopy.com

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.