0

I found this post:

Why is memcpy slower than a reinterpret_cast when parsing binary data?

where somebody uses reinterpret_cast to convert binary data to an integer. However (I presume) the number they are converting is at the 0th element in the char* array.

How could I use the above for situations where the binary number I want to convert is offset N bytes from the beginning of the char array?

I want to convert the binary number in as fewer CPU cycles as possible, hence my interest in reinterpret_cast and the above SO question.

Community
  • 1
  • 1
user997112
  • 29,025
  • 43
  • 182
  • 361
  • 2
    `*reinterpret_cast(data+byteOffset);` where `byteOffset` can be for example `positionInArray*sizeof(const int)`. That works when you want to access elements in the memory, I don't see any reason why reinterpreting them would change things :) – Paweł Stawarz Feb 12 '14 at 23:01
  • It should be noted that reinterpreting bytes by using `reinterpret_cast` to change pointer types is not supported by the C++ standard (and the equivalent in C, casting pointer types, is not generally supported by C). It can result in both alignment violations and aliasing violations. This can be done if the specific C/C++ implementation supports it. However, you should not rely on it in C/C++ generally; it is only suitable for specifically targeted implementations. To conform to the standard, bytes must be copied into a suitable object, as with `memcpy` (or, in C, a union may be used). – Eric Postpischil Feb 13 '14 at 15:45

2 Answers2

2

Just add a offset to the byte array address. Instead of x, cast x+123

But: Have you read the first line of the question (bold edit)?

TLDR: I forgot to enable compiler optimizations. With the optimizations enabled the performance is (nearly) identical.

deviantfan
  • 11,268
  • 3
  • 32
  • 49
  • Yeh- I had a look down and that person updated saying reinterpret_cast was still faster. He counted something like 56ms vs 60ms and i'm counting in terms of CPU cycles, not milli/microseconds (so its definitely worth using it) – user997112 Feb 12 '14 at 23:04
1

If you have a *array; initialized with your binary data then you can simply do this:

for (int offset = 0; offset < sizeof (array); offset++)
{
    ... = *reinterpret_cast<const int*>(array + offset);
}
cytoscope
  • 129
  • 2
  • Why the loop? He doesn't want to convert all of the array. And you're always assigning to `data`, this is equivalent to `data = *reinterpret_cast(array + sizeof(array)-1);` – Filipe Gonçalves Feb 12 '14 at 23:06
  • @FilipeGonçalves I perhaps falsely presumed that when he/she talked about 0-th element and accessing an n-th offset that was what he/she was going for in the long run... – cytoscope Feb 12 '14 at 23:09