tags:

views:

142

answers:

2

I have the following code:

    // Incrementer
    datastores.cmtDatastores.u32Region[0] += 1;

    // Decrementer
    datastores.cmtDatastores.u32Region[1] = (datastores.cmtDatastores.u32Region[1] == 0) ? 
        10 : datastores.cmtDatastores.u32Region[1] - 1;

    // Toggler
    datastores.cmtDatastores.u32Region[2] = 
        (datastores.cmtDatastores.u32Region[2] == 0x0000) ? 
        0xFFFF : 0x0000;

The u32Region array is an unsigned int array that is part of a struct. Later in the code I convert this array to Big endian format:

unsigned long  *swapL = (unsigned long*)&datastores.cmtDatastores.u32Region[50];
for (int i=0;i<50;i++) 
{
   swapL[i] = _byteswap_ulong(swapL[i]);
}

This entire code snippet is part of a loop that repeats indefinitely. It is a contrived program that increments one element, decrements another and toggles a third element. The array is then sent via TCP to another machine that unpacks this data.

The first loop works fine. After that, since the data is in big endian format, when I "increment", "decrement", and "toggle", the values are incorrect. Obviously, if in the first loop datastores.cmtDatastores.u32Region[0] += 1; results in 1, the second loop it should be 2, but it's not. It is adding the number 1(little endian) to the number in datastores.cmtDatastores.u32Region[0](big endian).

I guess I have to revert back to little endian at the start of every loop, but it appears there should be an easier way to do this.

Any thoughts?

Thanks,

Bobby

+3  A: 

The way I think about endian issues, is that there are numbers (when they are in the machine's endian order) and there are blobs of binary data (when they are not in the machines endian order).

When you think like this, you realize you can't increment a blob of binary data (or do any numeric operations on them). The only thing you can do with them is write the raw data or convert them to a number.

If you want to do numeric operations, the data must be a number so must be in the machine's endian order.

R Samuel Klatchko
+1  A: 

If the data always has to be bigendian to be sent out over TCP, then perhaps it would be simpler to leave the data in the array as always in bigendian order, and do the byte swap when you perform operations on the data. The increment would be come read from array, byteswap (to littleEndian), increment, byteswap (bigEndian), store to array.

dthorpe