开发者

Big->little (little->big) endian conversion of std::vector of structs

开发者 https://www.devze.com 2023-01-14 19:20 出处:网络
How can I perform endian conversion on vector of structs? For example: struct TestStruct { int nSomeNumber;

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-structs 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消