2016-03-14 30 views
-2

我有兩個字符值char_1char_2。現在我想將它們組合成16位有符號整數值,其中char_1包含MSB中的符號。2個字符來簽名短

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

|簽名字符1 |其餘的Char 1 | Char 2 |

我的嘗試是:

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

現在,我得到0 s ...

+0

請注意,您對整數大小的隱含假設是不可移植的。考慮從''使用固定寬度類型'std :: int8_t'和'std :: int16_t'。 – 5gon12eder

+0

假設'signed char'能夠保存一個有符號的8位數,並且假設short將保存一個有符號的16位數是可移植的。 –

回答

5

你需要按位orand

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

既然你還面臨着位,你應該也可以使用無符號類型(unsigned char,unsigned int,unsigned short)。

+0

我是個傻瓜。謝謝! – Christoph

+0

'char_2'必須是'(unsigned int)'。如果char在你的平臺上被簽名,並且char_1,char_2 == 1,0xff,那麼你將以(1 << 8)|結束。 (-1)......這可能不是你想要的! –

0

聯盟可能會實現更清潔的解決方案。

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)上運行良好,但是大端arch會打印char_2 char_1