gpt4 book ai didi

c++ - 如何从无符号变量写入和读取字节

转载 作者:行者123 更新时间:2023-11-28 00:38:38 27 4
gpt4 key购买 nike

这是我正在尝试做的事情:

我有两个整数

int a = 0; // can be 0 or 1
int b = 3; // can be 0, 1, 2 or 3

我也想拥有

unsigned short c

将变量存储在其中。

例如,如果我将 a 存储在 c 中,它将如下所示:

00000000
^ here is a

然后我需要将 b 存储在 c 中。它应该如下所示:

011000000
^^ here is b.

我还想在写完这些数字后读回这些数字。我该怎么做?

感谢您的建议。

最佳答案

假设那些是数字的二进制表示,并假设你真的想在 b 的右边有五个零

01100000
^^ here is b

(你让它 a 和 b 重叠的方式)

那么这是怎么做的

// write a to c
c &= ~(1 << 7);
c |= a << 7;

// write b to c
c &= ~(3 << 5);
c |= b << 5;

// read a from c
a = (c >> 7)&1;

// read b from c
b = (c >> 5)&3;

关于c++ - 如何从无符号变量写入和读取字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19917673/

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