virious
virious

Reputation: 571

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<TestStruct> vTestVector;

I know how to swap int values, but how to swap a whole vector of custom structs?

Upvotes: 1

Views: 2389

Answers (3)

j_random_hacker
j_random_hacker

Reputation: 51226

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.

Upvotes: 0

gbjbaanb
gbjbaanb

Reputation: 52659

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

Upvotes: 0

Goz
Goz

Reputation: 62323

As said in the comments. Endian swap each element in the vector:

auto iter = vTestVector.begin();
while( iter != vTestVector.end() )
{
    EndianSwap( iter->nSomeNumber );
    iter++;
}

Upvotes: 2

Related Questions