2012-09-12 30 views
0

我想從目標c中的字節數組中產生一個字符串。在我的課,我定義了以下常量字符stringWithBytes:length:encoding:正在產生錯誤的字符串長度

static const char HELLO_WORLD[] = {0x68,0x65,0x6c,0x6c,0x6f,0x20,0x77,0x6f,0x72,0x6c,0x64,0x0d,0x0a}; 

然後我在MyClass的方法,看起來像這樣:

+ (NSString *)stringFromBytes:(const void*)bytes 
{ 
    return [[NSString alloc] initWithBytes:bytes length:(sizeof(bytes)/sizeof(bytes[0])) encoding:NSUTF8StringEncoding]; 
} 

,如果我做這個

[MyClass stringFromBytes:HELLO_WORLD]; 
調用該方法

我得到一個字符串,看起來像「地獄」 - 即時通訊不知道如果我正確地做這個長度的一部分,並即時通訊假設這是問題。有關如何獲得這項工作的任何指導?

謝謝!

回答

0

這樣做:

+ (NSString *)stringFromBytes:(const char[])charbytes length:(NSUInteger)length 
{ 
    return [[NSString alloc] initWithBytes:charbytes length:length encoding:NSUTF8StringEncoding]; 
} 

使用這樣的:

NSString *str = [MyClass stringFromBytes:HELLO_WORLD length:sizeof(HELLO_WORLD)]; 
NSLog(@"%@",str); 
+0

不幸的是,這會導致不兼容的指針類型錯誤(向'char'類型的參數發送'const char [9]')。用char或char *取代const char也不行。 –

+0

彈出的錯誤現在是'sizeof on array函數參數將返回'const char *'的大小而不是'const char []' –

+0

檢查編輯答案完美工作現在 –

1

在你

+ (NSString *)stringFromBytes:(const void*)bytes 

方法,bytes只是一個指針,因此sizeof(bytes) == 4,這也解釋了爲什麼你看到地獄」。

指針沒有關於它指向的結構大小的信息。您必須提供大小作爲附加參數,或使用以NULL結尾的C字符串。

+0

投票,因爲這有助於我瞭解發生了什麼事情。謝謝! –

相關問題