2013-07-02 35 views
0

我有一個char數組,它保存的值爲0x4010,我希望將此值轉換爲無符號的short變量。 我這樣做是通過使用的atoi但越來越短值爲0字符數組類型轉換爲整數

unsigned short cvtValue = (unsigned short) atoi(aclDta); 

字符0x10的是DEL,我希望它是因爲這個原因。 十進制是6416

+0

'boost :: lexical_cast' –

+3

[類型轉換char到Unsigned short]可能重複(http://stackoverflow.com/questions/17430067/type-cast-char-to-unsigned-short) –

+1

如何能char數組保存一個值0x4010?這比char更大。它是否包含字符串「0x4010」。或者是字節0 0x40和字節1 0x10。或者反之亦然,這取決於您的架構? –

回答

4

你不需要轉換數據與atoi,只投它:

unsigned short cvtValue = *(unsigned short *)aclDta; 
+1

謝謝,作品很棒:) – Sijith

2

你所問的沒有意義。 ascii中的0x4010是'@',然後是'數據鏈接轉義'。

atoi,strtol等都是關於解析包含數字的ascii字符串 - @\DLE不是數字。

你真的似乎想要的是將0x4010字節視爲一個短。

這裏是一個廉價的方式:

cvtValue |= ((short)aclData[0]) << 8; 
cvtValue |= ((short)aclData[1]); 
+2

或使用@ PaulR的回答 – antiduh

1

我想發表評論,但顯然作爲新用戶我不能?無論如何,如果您可能將您的應用程序移植到具有不同endienness的平臺,antiduh的答案會更加正確。

char *str = "01"; 
unsigned short val = *(unsigned short *)str; 

在小endien系統val == 0x3130。在大endien系統val == 0x3031。

+0

聽說有些東西讓你開始+ 1 – petric