2012-03-07 185 views
1

因爲我對這個問題很陌生,這個問題可能看起來很瑣碎,所以請不要通過我父母的名字給我打電話......我有unsigned char和NSString ..我想分配char值的字符串...這是代碼片段..將unsigned char轉換爲NSString

NSString *passwordDgst = @"somepassword"; 
unsigned char passwordDgstchar[CC_SHA512_DIGEST_LENGTH]; 
CC_SHA512(passwordDgst, 
      passwordDgst.length, 
      passwordDgstchar); 

現在我想爲unsigned char passwordDgstchar的值賦給字符串passwordDgst。我怎樣才能做到這一點?

回答

4

這裏有一些問題。該功能需要二進制輸入並給出二進制輸出。您的代碼計算字符串對象的前12個字節的散列。您需要先將其轉換爲NSData。

NSData* input = [passwordDgst dataUsingEncoding: NSUTF8StringEncoding]; // Could use UTF16 or other if you like 
unsigned char passwordDgstchar[CC_SHA512_DIGEST_LENGTH]; 
CC_SHA512([input bytes], 
      [input length], 
      passwordDgstchar); 

passwordDgstchar現在包含原始二進制文件中的數據。要得到它說(十六進制):

NSMutableString* sha512 = [[NSMutableString alloc] init]; 
for (int i = 0 ; i < CC_SHA512_DIGEST_LENGTH ; ++i) 
{ 
    [sha512 appendFormat: @"%02x", passwordDgstChar[i]; 
} 
+0

非常感謝傑里米,但你能告訴我如何採取base64編碼,而不是十六進制的值?這將是非常有用的:) – Abhrajit 2012-03-09 06:33:53

+0

沒有問題..我反正..設計了我自己的功能:) – Abhrajit 2012-03-09 08:45:36