Converting a float to bytearray

后端 未结 2 839
有刺的猬
有刺的猬 2021-01-02 07:22

So, what I am trying to do is convert a float to a bytearray but I keep on receiving both no input, and EXTREME slowing/freezing of my computer. My code is

         


        
2条回答
  •  清歌不尽
    2021-01-02 07:44

    The result I would want from 5.1 is 0x40 a3 33 33 or 64 163 51 51. Not as a string.

    To get the desired list of integers from the float:

    >>> import struct
    >>> list(struct.pack("!f", 5.1))
    [64, 163, 51, 51]
    

    Or the same as a bytearray type:

    >>> bytearray(struct.pack("!f", 5.1))
    bytearray(b'@\xa333')
    

    Note: the bytestring (bytes type) contains exactly the same bytes:

    >>> struct.pack("!f", 5.1)
    b'@\xa333'
    >>> for byte in struct.pack("!f", 5.1):
    ...    print(byte)
    ...
    64
    163
    51
    51
    

    The difference is only in mutability. list, bytearray are mutable sequences while bytes type represents an immutable sequence of bytes. Otherwise, bytes and bytearray types have a very similar API.

提交回复
热议问题