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

如何实现uint8_t与int8_t互转、int8_t与uint16_t互相转换函数

实现思路

这三个函数的核心逻辑都是整数位模式的直接重解释,不需要手动计算数值偏移,当前主流设备均使用补码存储整数,直接操作位模式即可完全匹配需求,同时要注意规避有符号整数的符号扩展问题:

  • encode函数仅需将uint8_t的二进制位直接按int8_t规则解释
  • combine函数拼接时需先将int8_t转为uint8_t消除符号,避免负数被自动扩展为高位全1的16位值
  • explode函数仅需拆分uint16_t的高低8位,再分别重解释为int8_t即可
完整实现代码
#include <stdint.h>

// uint8_t转int8_t,设备读数写入存档时调用
int8_t encode(uint8_t input)
{
    return (int8_t)input;
}

// 两个int8_t合并为uint16_t,读取存档加载数据时调用
uint16_t combine(int8_t high_byte, int8_t low_byte)
{
    return ((uint16_t)(uint8_t)high_byte << 8) | (uint8_t)low_byte;
}

// uint16_t拆分为两个int8_t,应用数据导出到存档时调用
void explode(uint16_t input, int8_t *out_high_byte, int8_t *out_low_byte)
{
    *out_high_byte = (int8_t)(input >> 8);
    *out_low_byte = (int8_t)(input & 0xFF);
}
测试验证

提供的测试用例可全部通过:

  1. encode(255):uint8_t的255二进制为0xFF,强转int8_t后为-1,符合要求
  2. combine(7, -125):7转uint8_t为0x07,左移8位得0x0700;-125转uint8_t为0x83,按位或后得到0x0783,十进制为1923,符合要求
  3. explode(1923):1923的二进制为0x0783,高8位0x07转int8_t为7,低8位0x83转int8_t为-125,符合要求

内容的提问来源于stack exchange,提问作者Arron

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 18:54:04