pythonpython-bytearray

Use variable value as bytes array in Python


I want to implement socket client in Python. The server expects the first 8 bytes contain total transmission size in bytes. In C client I did it like this:

uint64_t total_size = zsize + sizeof ( uint64_t );
uint8_t* xmlrpc_call = malloc ( total_size );
memcpy ( xmlrpc_call, &total_size, sizeof ( uint64_t ) );
memcpy ( xmlrpc_call + sizeof ( uint64_t ), zbuf, zsize );

Where zsize and zbuff are size and data I want to transmit. In python I create byte array like this:

cmd="<xml>do_reboot</xml>"
result = deflate (bytes(cmd,"iso-8859-1"))
size = len(result)+8

What is the best to fill the header in Python? Without separating value to 8 bytes and copy it in loop


Solution

  • You could use the struct module, which will pack your data into binary data in the format you want

    import struct
    # ...your code for deflating and processing data here...
    
    result_size = len(result)
    # `@` means use native size, `I` means unsigned int, `s` means char[].
    # the encoding for `bytes()` should be changed to whatever you need
    to_send = struct.pack("@I{0}s".format(result_size), result_size, bytes(result, "utf-8"))
    

    See also: