简体   繁体   中英

float, int and str to byte array - python

I need to convert floats, ints and strings to byte arrays. This is Python2.7.

I know how to do this with floats and ints (for floats only , for example, struct.pack("{}f".format(len(float_array)), float_array) ) and with strings I am assuming one would just do list((map(ord, string)) for string in str_list) .

So, is there a way to do this for everything if it is all muddled up together. At the very minumum, I would like to be able to mix floats and ints together without having to iterate through each one.

If I do have to iterate through each one, how can I do this quickly and effectively. (Note: I have to run through a list of data - each datum of which, for now, is either a float or an int, however I also know which index should be either an int or a float (but I shouldn't need to know this) - and it would be preferable to simply take the list and convert it to another list of byte arrays (or really just a string like "\\xasdf\\xadf\\xasdf") in one fell swoop.)

Example: [1, 1.0] ==> byte array (or more complex [1, 1.0, "a"] ==> bytearray )

Note: I get an error when I do this:

import struct
num_list = [1, 1.0]
num_struct = struct.pack("2f", num_list)

but not when I do this:

import struct
num_list = [1.0, 2.0]
num_struct = struct.pack("2f", num_list)
def pack_all(lst):
    fmt = ''.join('i' if isinstance(x, int) else 'd' for x in lst)
    return struct.pack(fmt, *lst)

This handles integers and floats (double size). Strings are probably best handled with encode separately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM