将 int 存储在 2 个字符中

Store int in 2 chars

小问题:由于int是2个字节,char是1个字节,我想在2个char变量中存储一个int变量。 (就像第一个字符中的位 1 - 8,第二个字符中的位 9-16)。使用 C 作为编程语言。

我怎样才能做到这一点?会是这样的吗:

int i = 30543;
char c1 = (char) i;
char c2 = (char) (i>>8);

做这份工作?

我无法确定将 int 转换为 char 是否只会删除位 9-16。

这是从 c11 草案 n1570 中提取的

6.5.4 Cast operators

  1. If the value of the expression is represented with greater range or precision than required by the type named by the cast (6.3.1.8), then the cast specifies a conversion even if the type of the expression is the same as the named type and removes any extra range and precision.

因此转换确实会删除额外的位,但无论如何都不需要,因为该值将隐式转换为 char,并且以上内容仍然适用。

您只需要做:

char c1 = (char) ((i << 8) >> 8);

char c2 = (char) (i >> 8);