gpt4 book ai didi

c++ - 大小端问题

转载 作者:行者123 更新时间:2023-11-30 01:31:52 28 4
gpt4 key购买 nike

我有以下代码:

    // 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 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,但事实并非如此。它将数字 1(小端)添加到 datastores.cmtDatastores.u32Region[0](大端)中的数字。

我想我必须在每个循环开始时恢复到小端,但看起来应该有更简单的方法来做到这一点。

有什么想法吗?

谢谢,

鲍比

最佳答案

我对端序问题的看法是,有数字(当它们按照机器的端序排列时)和二进制数据的 blob(当它们不在机器的端序排列时)。

当您这样想时,您会意识到您不能递增二进制数据 block (或对它们执行任何数字运算)。您唯一能用它们做的就是写入原始数据或将它们转换为数字。

如果你想做数字运算,数据必须是一个数字,所以必须是机器的字节序。

关于c++ - 大小端问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2587686/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com