-3

I need to convert this array of bytes to string value? https://i.sstatic.net/lZMms.jpg

this array of bytes stored in memory like that: https://i.sstatic.net/1ciyu.jpg

the expected output -51.052277

19
  • 2
    StackOverflow is not here to write your code for you. What have you tried? Do you know how to convert strings to floats in general in C++? What do you see in your current string that looks different than "usual"? Also, raw C strings (char*) are assumed to be null terminated in a lot of places, so I hope you're keeping track of the size of that array in some other way, because all of the standard C-style functions are going to choke on it since you're using nulls in the middle. Commented Apr 14, 2022 at 1:28
  • 1
    How would you want to convert this? The data is 20 bytes, but floating point numbers in cpp are 4 or 8 bytes. Or if you are using some extended definitions 10 or 16 bytes none of which are the 20 bytes you show? Commented Apr 14, 2022 at 1:31
  • 2
    This array really looks like it's actually a string encoded in little endian UTF-16 (aka UTF-16LE). Commented Apr 14, 2022 at 1:31
  • 1
    @MathewFarrell I realise now, but the question is weirdly worded. What you want isn't to convert an array of bytes to float (essentially casting with extra steps), but to convert char16_t to float. Commented Apr 14, 2022 at 1:39
  • 1
    @Taekahn The question isn't whether it is the same on windows or not, but if someone were to find this some time from now this assumption cannot be made Commented Apr 14, 2022 at 2:03

1 Answer 1

2

I believe Etienne de Martel is correct: this looks like string of UTF-16LE code points, but without a 0 code point to terminate the string).

We can convert it to a floating point type something like this:

#include <iostream>
#include <vector>
#include <string>
#include <iomanip>

int main() {
    std::vector<char> inputs { 45, 0, 53, 0, 49, 0, 46, 0, 48, 0, 53, 0, 50, 0, 50, 0, 55, 0, 55, 0  };

    wchar_t const* data = reinterpret_cast<wchar_t const*>(inputs.data());

    std::wstring cp(data, inputs.size()/2);

    double d = std::stod(cp);

    std::cout << std::setw(10) << std::setprecision(10) << d << '\n';
}

This depends on wchar_t meaning UTF-16LE, which is the case with the compiler I'm using, but isn't required. In theory, you should probably use char16_t and std::u16string instead, but that doesn't work out well either (it'll create the string all right, there's no std::stod for std::u16string).

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.