将一个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;
}
这是因为您的平台的端序。多字节uint16_t
的字节存储在地址空间最低字节优先。您可以通过对大于256的数字执行相同的程序来了解发生了什么:
uint16_t my_num = 0xABCD;
结果是0xCD
在第一个字节,0xAB
在第二个字节。
可以使用hton
/ntoh
族的函数强制使用特定的端序。
相关文章:
- 程序错误地读取了二进制文件的一个字节
- 解压缩串联的 zlib 流而不读取下一个字节
- 一次读取一个字节的 unicode
- 如何从 int 一次写入一个字节的文件?C++
- 如何将一个字节数组正确地恢复为C 中的对象
- 我正在尝试修改一个字节数组并通过 JNI 将其从 c++ 发送到 java
- 快速简单的方法,以C++为单位一次读取一个字节的 stdin
- 如何编写一个字节表示为c 中的文件
- 两个 4 位位字段加起来不等于一个字节的大小 - 如何修复?
- GCC 编译器一个字节中有多少位
- 处理Huffman压缩/减压中的最后一个字节
- 如何在-120到120之间更改int到char(或其他简单保存为一个字节的简单方法)
- Winapi WriteFile 函数写入一个字节
- C RLE BMP压缩跳过了最后一个字节
- mbtowc在osx上总是返回一个字节
- C 将一个字节与字母进行比较
- 有可能在c++中创建一个占用不到一个字节内存的类型吗
- Qt串行端口有时会丢失最后一个字节
- (C++)ReadProcessMemory-读取一个字节时出现问题
- 将一个字节数组从Unity C#传递到C++库方法中