e.g given vector<uint8> of length 100, how create new vector<uint16> of 50 elements. preferably without copying?
(edit: info comments)
to illustrate:
i have uint16 grayscale image file, 3rd party lib returns vector of uint8. every 2 bytes = 1 pixel. practical me work vector of uint16. think difference between vector<uint8> , corresponding vector<uint16> bytes read in "concatenated" manner (i.e. chunks of 2 bytes = 1 value).
i loop , combine every 2 elements new vector element, seems inefficient, since memory layout same. hoping combine cast , maybe move constructor create vector<uint16> --without copying original vector<uint8> bytes again.
edit 2: dispel possible misunderstandings drew picture, forgive poor ascii art :)
container of uint8 values in memory:
[ _ ] | [ _ ] | [ _ ] | [ _ ] ...
|^^|
accessing element = accessing 1 byte
container of uint16 values in memory sequence of bytes;
[ _ ] | [ _ ] | [ _ ] | [ _ ] ...
|^ ^ ^ ^ ^|
accessing element = accessing 2 bytes (lets system read big-endian)
i have sequence of bytes in vector v1. want v2 of different type can access them differently. if turns out uint16 values read little-endian still work that.
edit 3: far seems answer black best understanding (i accept later if nothing changes), still seems odd there no simple or stl solution this. though prompt input , patience attempts @ explaining myself.
vector<std::uint8_t> hold std::uint8_t* whilst vector<std::uint16_t> std::uint16_t*. want share 2 pointers , give different interpretations, like
auto ptr = reinterpret_cast<std::uint16_t*>( vectorofuint8.data() ) this fine long don't read/write through pointer because such operation cause undefined behavior due strict-aliasing rule. need copy, can optimized efficient simd. if compiler can't automatically, can use intrinsics or unroll it:
- read 2 elements v1 v2 96 (48 in v2) manually
- loop on v2 , read 4 (i += 48 / 4 = 12) or 8 (i += 48 / 8 = 6) elements @ time
you disable strict-aliasing rule, though that's compiler-specific , hence not standard , portable.
Comments
Post a Comment