Big->little (little->big) endian conversion of std::vector of structs
How can I perform endian conversion on vector of structs?
For example:
struct TestStruct
{
int nSomeNumber;
char sSomeString[512];
};
std::vector<T开发者_运维技巧estStruct> vTestVector;
I know how to swap int values, but how to swap a whole vector of custom structs?
As said in the comments. Endian swap each element in the vector:
auto iter = vTestVector.begin();
while( iter != vTestVector.end() )
{
EndianSwap( iter->nSomeNumber );
iter++;
}
#include <boost/foreach.hpp>
BOOST_FOREACH(TestStruct& s, vTestVector)
{
SwapEndian(s.nSomeNumber);
}
Give or take, that'll do it. You don't need to affect the char string, just the numeric variable. s.
If you're looking for a general way to do this (i.e. a single piece of template metaprogramming code that would let you iterate over the elements of a plain struct
, recursing into sub-struct
s and converting multibyte integer values whenever they are encountered) then you're out of luck. Unfortunately you can't iterate over elements of an arbitrary struct
in C++ -- so you'll need to write special-case code for each different type.
精彩评论