Concatenate a string as binary bytes

MRAB python at mrabarnett.plus.com
Tue Dec 14 15:02:49 EST 2010


On 14/12/2010 19:50, Jaime Fernández wrote:
> Hi
>
> To build a binary packet (for SMPP protocol), we have to concatenate
> different types of data: integers, floats, strings.
>
> We are using struct.pack to generate the binary representation of each
> integer and float of the packet, and then they are concatenated with the
> + operand.
> However, for strings we directly concatenate the string with +, without
> using struct.
>
> Everything works with python 2 except when string encoding is
> introduced. Whenever, a non ASCII char appears in the string, an
> exception is launched. In python 3, it's not possible to do this trick
> because all the strings are unicode.
>
> What would be the best approach to:
>   - Support non-ascii chars (we just want to concatenate the binary
> representation of the string without any modification)
>   - Compatibility between python 2 and python 3.
>
I'd say encode to UTF-8.



More information about the Python-list mailing list