简体   繁体   English

解释std :: vector <char> 作为std :: vector <short>

[英]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: 我想将其转换为std::vector<short> s ,以便元素可以:

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

Because if you combine the chars 0 and 1 it makes 256 in short . 因为当你将字符01这使得256short

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. 如果您想要将char数组看作是short的一半的little-endian表示形式,而不管实现的字节顺序如何,那么它会稍微复杂一些。 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. 理想情况下,您的解决方案应该编写一个从两个字符创建一个short的函数,而不依赖于平台字节序或平台上short的大小。

Easier to do unsigned where you can simply do something like ptr[i] + static_cast<unsigned short>( ptr[i+1] ) << 8; 进行无符号签名更容易,您可以在其中简单地执行以下操作: 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) (即,如果char向量的char数为奇数,它将忽略最后一个)

Note data is only a member of vector in C++11. 注意data只是C ++ 11中vector的成员。 For older version replace with &c[0] 对于较旧的版本,请替换为&c[0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM