简体   繁体   中英

how to convert python float to bytes to be interpreted in C++ programm

I need to build a python script that export data to a custom file format. This file is then read by a cpp programm (I have the source code, but cannot compile it).

custome file fomat spec:

  • The file must be little endian.
  • The float must be 4 bytes long.

I'm failing at exporting python float to bytes. thus crashing the cpp app without any error trace. If i try to fill all the float with 0 it load perfectly fine, but if i try anything else it crashes.

This is how the cpp app read the float

double Eds2ImporterFromMemory::read4BytesAsFloat(long offset) const
{
    // Read data.
    float i = 0;
    memcpy(&i, &_data[offset], 4);

    return i;
}

And I try to export the python float as follows:

def write_float(self, num):
    # pack float 
    self.f.write(struct.pack('<f', float(num)))

And also like this as some people suggested me:

def write_float(self, num):
    # unpack as integer the previously pack as float number    
    float_hex = struct.unpack('<I', struct.pack('<f', num))[0]
    self.f.write(float_hex.to_bytes(4, byteorder='little'))

But it fails every time. I'm not a cpp guy as you can see. Do you have an idea on why my python script is not working.

Thanks in advance

Please excuse me for being really bad at python, but i tried to produce your desired result and it works fine for me.

The python code:

import struct

value = 13.37

ba = bytearray(struct.pack("f", value))  
for b in ba:
    print("%02x" % b)

I imagine if you would just concat that (basically write the hexadecimal representation to a file in that order), it would work just fine.

Either way, it will output

85
eb
55
41

Which i put in an array of unsigned chars and used memcpy in the same way your C++ code did:

unsigned char data[] = {0x85, 0xeb, 0x55, 0x41};

float f;
memcpy(&f, data, sizeof(float));

std::cout << f << std::endl;
std::cin.get();

Which will output 13.37 as you would expect. If you cannot reproduce the correct result this way, i suspect that the error occurs somewhere else, in which case it would be helpful to see how the format is written by python and how it's read by C++.

Also, keep in mind that there are several ways to represent the byte array, like:

\\x85eb5541 , 0x85, 0xeb, 0x55, 0x41 , 85eb5541 and so on. To me it seems very likely that you just aren't outputting the correct format and thus the "parser" crashes.

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