gpt4 book ai didi

c - 将 2 个带符号的短裤存储在一个无符号整数中

转载 作者:行者123 更新时间:2023-12-01 08:56:44 24 4
gpt4 key购买 nike

这是给定的:

signed short a, b;
a = -16;
b = 340;

现在我想将这 2 条签名短裤存储在一个 unsigned int 中,稍后再次检索这 2 条签名短裤。我尝试了这个,但生成的短裤不一样:

unsigned int c = a << 16 | b;

signed short ar, br;
ar = c >> 16;
br = c & 0xFFFF;

最佳答案

OP 几乎是对的

#include <assert.h>
#include <limits.h>

unsigned ab_to_c(signed short a, signed short b) {
assert(SHRT_MAX == 32767);
assert(UINT_MAX == 4294967295);
// unsigned int c = a << 16 | b; fails as `b` get sign extended before the `|`.
// *1u insures the shift of `a` is done as `unsigned` to avoid UB
// of shifting into the sign bit.
unsigned c = (a*1u << 16) | (b & 0xFFFF);
return c;
}

void c_to_ab(unsigned c, signed short *a, signed short *b) {
*a = c >> 16;
*b = c & 0xFFFF;
}

关于c - 将 2 个带符号的短裤存储在一个无符号整数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41064702/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com