2

This question is a follow up to C++ - Convert array of floats to std::string.

How to convert a std::string back to float array that was converted to string using reinterpret_cast.

0

1 Answer 1

2

Get the string's backing data pointer from the c_str() method. Then reinterpret_cast it back to the float pointer.

const float* array_of_floats = reinterpret_cast<const float*>(str.c_str());
int len = str.size() / sizeof(float);

In general, serializing binary data (such as array of floats) into string can work, but is at best weird and more likely ill-advised. You are better off using std::vector<uint8_t> as an array of bytes to hold your floating pointer data instead of an instance of a string.

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

4 Comments

Getting following error main.cpp:20:16: error: reinterpret_cast from 'const std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::value_type *' (aka 'const char *') to 'float *' casts away qualifiers float *d = reinterpret_cast<float*>(s.c_str()); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ahhh… I forgot. c_str() returns a const char*. Therefore, you need to cast to a const float*. Answer updated.
@SaurabhSaxena be advised that the array_of_floats pointer is only valid as long as the underlying string exists and is unchanged. It might be better to copy the floats into a separate array instead of relying on a pointer to the string data.
@john I am planning to store string in db.

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.