将 16 位整数复制到两字节数组
Copying a 16 bit integer to a two byte array
我想知道为什么当我将一个 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;
}
提前致谢。
这是因为您的平台endianness。多字节 uint16_t
的字节存储在地址 space 最低字节优先。您可以通过使用大于 256 的数字尝试相同的程序来查看发生了什么:
uint16_t my_num = 0xABCD;
结果将在第一个字节中包含 0xCD
,在第二个字节中包含 0xAB
。
您可以使用 hton
/ntoh
family.
中的函数强制特定的字节顺序
我想知道为什么当我将一个 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;
}
提前致谢。
这是因为您的平台endianness。多字节 uint16_t
的字节存储在地址 space 最低字节优先。您可以通过使用大于 256 的数字尝试相同的程序来查看发生了什么:
uint16_t my_num = 0xABCD;
结果将在第一个字节中包含 0xCD
,在第二个字节中包含 0xAB
。
您可以使用 hton
/ntoh
family.