3

I'm required to send a 32bit integer over a serial connection like so: 0xc6bf6f34 should become: b'\xc6\xbf\x6f\x34'.

To that end, I created this, but, as always after such coding, I wondered if it's pythonicism could be improved with something in the standard libary:

def ltonlba(value):
    ''' ltonlba : Long to Network Long Byte Array '''
    from socket import htonl
    value = htonl(value)
    ba = b''
    for i in range(4):
            ba += chr((value) & 0xff)
            value >>= 8
    return ba
0

1 Answer 1

6

If you're using Python 3.2+, you can use int.to_bytes:

>>> 0xc6bf6f34.to_bytes(4, 'little')  # 4 bytes = 32 bits
b'4o\xbf\xc6'
>>> 0xc6bf6f34.to_bytes(4, 'little') == b'\x34\x6f\xbf\xc6'
True

Otherwise, you can use struct.pack with <I format (<: little-endian, I: 4-bytes unsigned integer , see Format strings - struct module doc):

>>> import struct
>>> struct.pack('<I', 0xc6bf6f34)
b'4o\xbf\xc6'

UPDATE / NOTE: If you want to get big-endian (or network-endian), you should specify 'big' with int.to_bytes:

0xc6bf6f34.to_bytes(4, 'big')  # == b'\xc6\xbf\x6f\x34'

and > or ! with struct.pack:

struct.pack('>I', 0xc6bf6f34)  # == b'\xc6\xbf\x6f\x34'  big-endian
struct.pack('!I', 0xc6bf6f34)  # == b'\xc6\xbf\x6f\x34'  network (= big-endian)
Sign up to request clarification or add additional context in comments.

5 Comments

Does the struct.pack() solution work with Python 3.2+ as well?
@Jamie, It works with both in Python 2.x, 3.x. I tested it in Python 2.7.13 / 3.5.3 / 3.6.1.
@Jamie, I rolled back your change. You want little little-endian according to your question.
@Jamie, If you specify network-endian (or big-endian) , you will get b\xc6\xbf\x6f\x34 instead.
@Jamie, I updated the answer to explicitly mention it.

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.