Converting a float to bytearray

后端 未结 2 733
有刺的猬
有刺的猬 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:40

    It depends what you want, and what you are going to do with it. If all you want is a bytearray then:

    import struct
    
    value = 5.1
    
    ba = bytearray(struct.pack("f", value))  
    

    Where ba is a bytearray. However, if you wish to display the hex values (which I suspect), then:

    print([ "0x%02x" % b for b in ba ])
    

    EDIT:

    This gives (for value 5.1):

    ['0x33', '0x33', '0xa3', '0x40']
    

    However, CPython uses the C type double to store even small floats (there are good reasons for that), so:

    value = 5.1
    ba = bytearray(struct.pack("d", value))   
    print([ "0x%02x" % b for b in ba ])
    

    Gives:

    ['0x66', '0x66', '0x66', '0x66', '0x66', '0x66', '0x14', '0x40']
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题