2个字符签名短

2 chars to signed short

我有两个字符值 char_1char_2。现在我想将它们组合成一个 16 位有符号整数值,其中 char_1 包含 MSB 中的符号。

|SGN|Bit 6|Bit 5|Bit 4|Bit 3|Bit 2|Bit 1|Bit 0|Bit 7|Bit 6|Bit 5|Bit 4|Bit 3|Bit 2|Bit 1|Bit 0|

|符号字符 1 |字符 1 的其余部分 |字符 2 |

我的尝试是:

signed short s = (((int)char_1) << 8) & (int)char_2;

现在 s...

我得到 0

你需要按位 or 而不是 and

(((int)char_1) << 8) | (int)char_2;

由于您还要处理位,因此您可能也应该使用无符号类型(unsigned char、unsigned int、unsigned short。)

工会可能会实现更清洁的解决方案。

typedef union { short int s; char c[2];} Data;

int main (){
        Data d;
        d.c[0]=char_2;
        d.c[1]=char_1;
}

注意:这对您来说可能不够便携,因为索引的顺序取决于体系结构字节顺序。我的示例在 Little endian archs(即 Intel 0x86)上运行良好,但 big endian archs 将打印 char_2 char_1.