我有以下代码:大端和小端的问题
// 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;
的u32Region阵列是一个unsigned int数组,它是一个结构的一部分。后来在我的代码这个数组转换为大端格式:
unsigned long *swapL = (unsigned long*)&datastores.cmtDatastores.u32Region[50];
for (int i=0;i<50;i++)
{
swapL[i] = _byteswap_ulong(swapL[i]);
}
整个代码段是重复的循环无限期的一部分。这是一个人为设计的程序,增加一个元素,减少另一个元素,切换第三个元素。然后该数组通过TCP发送到另一台机器,该机器将这些数据解包。
第一个循环正常工作。之后,由于数据采用大端格式,当我“增加”,“减少”和“切换”时,这些值不正确。显然,如果在第一个循环datastores.cmtDatastores.u32Region[0] += 1;
的结果为1,第二个循环应该是2,但事实并非如此。它将datastores.cmtDatastores.u32Region[0]
(大端)中的数字加到数字1(小端)上。
我想我必须在每个循环的开始时回到little endian,但它似乎应该有一个更简单的方法来做到这一点。
有什么想法?
感谢,
鲍比