简体   繁体   中英

Reading value from buffer efficiently

I have a std::vector<char> buffer in memory with a number at a specific offset, eg

00 00 00 00 00 00 00 00 00 33 2E 31 34 99 99 99 .........3.14™™™

I know the end and start offset to read the double/float value, but right now I'm copying the relevant part with std::copy() into a std::string and then calling std::stod . My question is: how can I make this faster?

There must be a way to avoid the copy.. for instance: can I point a stream to a specific offset in another buffer? Or something similar perhaps

If you know the offset then simply:

vector<char> data;
// ... snip ...
char *endp = null;
double result = strtod(&data[offset],&endp);

Note: This assumes that the number is followed by non-numeric characters (or end of string).

If the numbers were delimited, then using strtod directly on the buffer like Let_Me_Be suggests is efficient. However, since the numbers are not delimited, you cannot use strtod directly.

If the buffer is zero (or eof) terminated, then you can simply modify it, by adding the terminator after the number, and then restore the original character, like bolov suggested. Since the end offset is part of the number, there's always at least the terminator after it, so offset_end won't overflow. The following code assumes that offset_end is one past the last character. If it's the last character, then simply use + 1 .

auto original = data[offset_end];
data[offset_end] = '\0';
auto result = strtod(&data[offset_start], nullptr);
data[offset_end] = original;

Even, if the buffer is not terminated, you can still do that, but only if the number is not at the very end. If it is, or if you don't know where the buffer ends, or the buffer is const , then your current solution is as efficient as it gets.

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