将一个16位整数复制到一个两字节数组

Copying a 16 bit integer to a two byte array

本文关键字:一个 字节 字节数 数组 16位 整数 复制      更新时间:2023-10-16

我想知道为什么当我将16位数字复制到两个字节数组时,它只会复制到数组的第一个索引。我的代码如下:

#include <iostream>
#include <stdint.h>
#include <stdio.h>
#include <cstring>

using namespace std;

int main(){
    uint16_t my_num = 1; // This should be 0000 0000 0000 0001, right?
    unsigned char my_arr[2]; // This should hold 16 bits, right?
    memcpy(my_arr, &my_num, sizeof(my_num)); // This should make my_arr = {00000000, 00000001}, right?
        printf("%x ", my_arr[0]);
        printf("%x ", my_arr[1]);
        cout << endl;
        // "1 0" is printed out

        return 0;
}

这是因为您的平台的端序。多字节uint16_t的字节存储在地址空间最低字节优先。您可以通过对大于256的数字执行相同的程序来了解发生了什么:

uint16_t my_num = 0xABCD;

结果是0xCD在第一个字节,0xAB在第二个字节。

可以使用hton/ntoh族的函数强制使用特定的端序。