You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何改写自定义Mymem_cpy函数实现从无零字节数组生成补零整数数组?

解决方案

首先纠正你现有代码中的两处错误:

  • unsigned char bytes[8]{ 179, 16, 0, 0, 0, 40, 92, 0, 0 }; 初始化元素数量超过数组长度(声明8个元素但给了9个值),需修正为unsigned char bytes[8]{ 179, 16, 0, 0, 40, 92, 0, 0 };
  • 调用Mymem_cpy时参数语法错误,正确写法应为Mymem_cpy(IntArray, bytes, 8);

针对你的需求,有两种改写方案:

方案一:针对16位无符号数转32位int的专用实现

这个方案直接匹配你的业务场景,明确将每2字节的无符号16位数字扩展为4字节的int,自动高位补零,同时处理小端字节序(符合你给出的示例结果逻辑):

#include <stdint.h>

void* Mymem_cpy(void* dest, const void* src, int src_byte_count) {
    if (dest == NULL || src == NULL) return NULL;

    uint32_t* int_dest = (uint32_t*)dest;
    const uint8_t* byte_src = (const uint8_t*)src;

    int num_16bit_vals = src_byte_count / 2;
    for (int i = 0; i < num_16bit_vals; i++) {
        // 按小端字节序拼接16位值:低字节在前,高字节在后
        uint16_t raw_val = (uint16_t)(byte_src[2*i + 1] << 8 | byte_src[2*i]);
        // 扩展为32位int,自动高位补零
        int_dest[i] = (uint32_t)raw_val;
    }

    return dest;
}

使用示例:

unsigned char bytesInput[4]{ 179, 16, 40, 92 };
int IntArray[2];
// 传入源字节数组、目标int数组、源总字节数
Mymem_cpy(IntArray, bytesInput, sizeof(bytesInput));

// 结果:IntArray[0] = 4275,IntArray[1] = 23592,与带零数组的拷贝结果一致

方案二:通用型补零拷贝函数

如果需要更通用的场景(任何源字节数小于目标字节数时自动补零),可以修改函数增加目标总字节数参数,先拷贝源数据,剩余字节填充零:

void* Mymem_cpy(void* dest, const void* src, int src_bytes, int dest_total_bytes) {
    if (dest == NULL) return NULL;

    unsigned char* char_dest = (unsigned char*)dest;
    const unsigned char* char_src = (const unsigned char*)src;

    // 先拷贝源中存在的字节
    int copy_len = (src_bytes < dest_total_bytes) ? src_bytes : dest_total_bytes;
    for (int i = 0; i < copy_len; i++) {
        char_dest[i] = char_src[i];
    }

    // 剩余字节补零
    for (int i = copy_len; i < dest_total_bytes; i++) {
        char_dest[i] = 0;
    }

    return dest;
}

使用示例:

unsigned char bytesInput[4]{ 179, 16, 40, 92 };
int IntArray[2];
// 传入源、目标、源字节数、目标总字节数
Mymem_cpy(IntArray, bytesInput, sizeof(bytesInput), sizeof(IntArray));

这个方案的效果和直接拷贝带零的8字节数组完全一致,因为前4字节从源拷贝,后4字节自动补零。

内容的提问来源于stack exchange,提问作者Евгений Федоров

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 22:15:04