1

I am trying to use C++ sending a fixed length float array and use python to get it

Here is my C++ client, where sConnect is a SOCKET object

    float news[2];
    news[0] = 1.2;
    news[1] = 2.56;
    char const * p = reinterpret_cast<char const *>(news);
    std::string s(p, p + sizeof news);
    send(sConnect, &s[0], sizeof(news), 0);

And at python server my code is like

import socketserver


class MyTCPHandler(socketserver.BaseRequestHandler):
    def handle(self):

    self.data = self.request.recv(8).strip()
    print (self.data)

if __name__ == "__main__":
   HOST, PORT = "127.0.0.1", 9999
   print("listening")
   server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
   server.serve_forever()

And the data I got at python is like

b'\x9a\x99\x99?\n\xd7#@'

How to recover this back to the original float data I sent? Or is there a better way to send and receive the data?

1 Answer 1

2

You can use the struct module to unpack the byte data.

import struct
news = struct.unpack('ff', b'\x9a\x99\x99?\n\xd7#@')
print(news)

With your code:

import struct
import socketserver

class MyTCPHandler(socketserver.BaseRequestHandler):
    def handle(self):
        self.data = self.request.recv(8).strip()
        news = struct.unpack('ff', self.data)
        print(news)

The first argument to struct.unpack, 'ff', is the format string specifying the expected layout of the data, in this case 2 floats. See https://docs.python.org/3/library/struct.html for other format characters.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.