小编hec*_*rot的帖子

将uint8_t转换为sint8_t

在便携式C中将"uint8_t"转换为"sint8_t"的最佳方法是什么?

那是我提出的代码......

#include <stdint.h>

sint8_t DESER_SINT8(uint8_t x)
(
  return
     (sint8_t)((x >= (1u << 8u))
               ? -(UINT8_MAX - x)
               : x);
)
Run Code Online (Sandbox Code Playgroud)

有更好/更简单的方法吗?也许没有使用条件的方式?

编辑:谢谢你们.总而言之,我已经学到了什么......

  • sint8_t 真的叫 int8_t
  • 128是表达1 << 7而不是表达1 << 8
  • 2s补充是"一个人否定"

:)

所以这是我原始代码的更新版本:

#include <stdint.h>

int8_t DESER_INT8(uint8_t x)
(
  return ((x >= (1 << 7))
          ? -(UINT8_MAX - x + 1)
          : x);
)
Run Code Online (Sandbox Code Playgroud)

c c++ serialization

4
推荐指数
3
解决办法
4486
查看次数

标签 统计

c ×1

c++ ×1

serialization ×1