简体   繁体   English

为什么 std::copy 以相反的顺序

[英]why std::copy in reverse order

I want to copy a sequence of bytes into integer values, presumably they will whim with the port's UPD我想将一个字节序列复制到 integer 值中,大概他们会随端口的 UPD 突发奇想

#include <iostream>
#include <cstring>

int main()
{
    uint8_t arr[8];
    uint32_t arrNew[2];

    arr[0] = 0x11;
    arr[1] = 0x22;
    arr[2] = 0x33;
    arr[3] = 0x44;
    arr[4] = 0x55;
    arr[5] = 0x66;
    arr[6] = 0x77;
    arr[7] = 0x88;

    memcpy(arrNew, arr, 8);

    std::cout << std::hex << arrNew[0] << "\n"; //out: 0x44332211
    std::cout << std::hex << arrNew[1] << "\n"; //out: 0x88776655

    return 0;
}

It should be: arrNew[0] = 0x11223344 arrNew[1] = 0x55667788.应该是:arrNew[0] = 0x11223344 arrNew[1] = 0x55667788。

This is a very fragile thing to do.这是一件非常脆弱的事情。 As mentioned in one of the comments, it depends on the endianess.正如其中一条评论所述,这取决于字节序。 The number 0x01020304 can be stored:可以存储数字 0x01020304:

x01 x02 x03 x04 x01 x02 x03 x04

But on others, it's the other way around.但在其他人身上,情况恰恰相反。 This is big-endian versus little-endian.这是大端与小端。 A google for little endian vs. big endian will result in some great pages to read, so I'm not going to write it all here. little endian vs. big endian的谷歌将导致一些很棒的页面可供阅读,所以我不打算在这里全部写出来。

On the hardware you're using, the endianess is opposite of what you expect.在您使用的硬件上,字节序与您的预期相反。

Basically, you can't assume.基本上,你不能假设。 There are methods for dealing with network byte order.有处理网络字节顺序的方法。 There's more information in this question: How do you write (portably) reverse network byte order?在这个问题中有更多信息: How do you write (portable) reverse network byte order?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM