简体   繁体   中英

Interpret std::vector<char> as std::vector<short>

Suppose I have a vector:

std::vector <char> c;
c.push_back(0);
c.push_back(1);
c.push_back(0);
c.push_back(1);

I want to convert this into std::vector<short> s So that elements would:

s[0] == 256;
s[1] == 256;

Because if you combine the chars 0 and 1 it makes 256 in short .

Is there a better way to convert the vectors like this?

Assuming you're happy with implementation-specific behavior, that could be undefined on unusual architectures, then I'd do it like this:

short *ptr = reinterpret_cast<short*>(c.data());
std::vector<short> s(ptr, ptr+c.size()/2);

If what you want is to treat the array of char as a little-endian representation of half as many short , regardless of the endian-ness of the implementation, then it's a little more complicated. Something like this:

std::vector<short> s;
s.reserve(c.size() / 2);
for (size_t idx = 0; idx < c.size(); idx += 2) {
    s.push_back(c[idx] & 0xff + static_cast<unsigned>(c[idx+1]) << 8);
}

Beware that this still involves a conversion from unsigned to signed type, so it's still implementation dependent. You need more bit-twiddling to make it truly portable.

Your solution should ideally write a function that creates a short from two chars, and not rely in platform endianness or the size of short on your platform.

Easier to do unsigned where you can simply do something like ptr[i] + static_cast<unsigned short>( ptr[i+1] ) << 8;

If you just want to copy the data directly by casting, it is trivial.

const short * data = reinterpret_cast< const short * > ( c.data() ); 
std::vector< short > s( data, data + c.size() / 2 );

It will "truncate" the last character off your vector if its size is odd. (ie if the char vector has an odd number of chars it will ignore the last one)

Note data is only a member of vector in C++11. For older version replace with &c[0]

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