如何将unsigned int合并到字节数组,构造aabbstream格式的字节序列?
实现
aabbstream格式的字节数组拼接 核心逻辑
要达成需求,需按以下步骤操作:
- 从
unsigned int变量a、b中提取目标两个字节(注意字节序:是取高16位还是低16位,需根据实际业务场景确定) - 将提取的字节按
aa、bb的顺序写入结果数组头部 - 把原
byte stream的内容追加到结果数组末尾
C语言实现示例
假设我们取unsigned int的低16位(最后两个字节),并按小端序存储(若需大端序,调整字节提取顺序即可):
#include <stdint.h> #include <string.h> // 定义Byte为uint8_t的别名 typedef uint8_t Byte; // 拼接函数:返回拼接后的字节数组(调用方需自行释放内存) Byte* merge_to_aabbstream(unsigned int a, unsigned int b, const Byte* stream, size_t stream_len, size_t* out_total_len) { // 计算总长度:a的2字节 + b的2字节 + 原stream长度 *out_total_len = 2 + 2 + stream_len; Byte* result = (Byte*)malloc(*out_total_len); if (!result) return NULL; // 提取a的低16位字节,小端序存储(先存低字节,再存高字节) result[0] = (Byte)(a & 0xFF); result[1] = (Byte)((a >> 8) & 0xFF); // 提取b的低16位字节,小端序存储 result[2] = (Byte)(b & 0xFF); result[3] = (Byte)((b >> 8) & 0xFF); // 追加原stream内容 memcpy(result + 4, stream, stream_len); return result; }
关键注意点
- 字节序调整:如果需要大端序(先存高字节,再存低字节),只需交换每个变量两个字节的存储顺序,比如a的大端存储写法:
result[0] = (Byte)((a >> 8) & 0xFF); result[1] = (Byte)(a & 0xFF); - 内存管理:示例中用
malloc分配内存,调用方必须记得用free释放,避免内存泄漏 - 高位数据提取:如果
unsigned int的高16位有有效数据,需要提取高16位的话,将位操作改为(a >> 16) & 0xFF和(a >> 24) & 0xFF(小端序)即可
内容的提问来源于stack exchange,提问作者M Rajoy
相关产品推荐
相关产品推荐

