Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我正在实现 C 代码以将 16 位符号和幅度整数复制到 8 位符号和幅度整数。这甚至可能吗?有人可以解释一下如何做到这一点吗?
代码片段:
int16_t a = 0x1234; int8_t b, c;
如何将前两位数字复制到变量b,然后将后两位数字复制到变量c?
您可以使用该语言的按位运算符:您需要将数字 8 和 0 向右移动以分别获得第一个和第二个数字(并且您还应该用 255 屏蔽它们,以便准确提取一个字节):
int16_t i = 0x1234; uint16_t n = i; // because shifting the sign bit invokes UB int8_t hi = ((i >> 8) & 0xff); int8_t lo = ((i >> 0) & 0xff);