2012-08-09 98 views
0

如果我有一個字符串,我如何在Objective-C中將值轉換爲十六進制?同樣,我怎樣才能從十六進制字符串轉換爲字符串?如何將字符串轉換爲十六進制?

+0

你能更具體的上下文嗎?什麼格式的輸入(NSString,NSData,NSNumber,C風格的字符等),你需要什麼樣的輸出? – 2012-08-09 05:45:34

+0

它是char *到十六進制轉換,反之亦然 – 012346 2012-08-09 05:46:50

+1

'strtol(3)'怎麼辦? – 2012-08-09 05:56:25

回答

1

作爲一個練習,如果它有幫助,我寫了一個程序來演示如何在純C中執行此操作,該操作在Objective-C中是100%合法的。我在stdio.h中使用了字符串格式化函數來進行實際的轉換。

請注意,這可以(應該?)針對您的設置進行調整。它將在char-> hex(例如將'Z'轉換爲'5a')時創建一個兩倍於傳入字符串的字符串,而另一個字符串的長度則爲一半。

我寫了這樣的代碼,你可以簡單地複製/粘貼,然後編譯/運行來玩弄它。這裏是我的示例輸出:

enter image description here

我最喜歡的方式,包括C在Xcode是使.h文件報關單從實施.c文件分離功能。見評論:

#include <string.h> 
#include <stdlib.h> 
#include <stdio.h> 

// Place these prototypes in a .h to #import from wherever you need 'em 
// Do not import the .c file anywhere. 
// Note: You must free() these char *s 
// 
// allocates space for strlen(arg) * 2 and fills 
// that space with chars corresponding to the hex 
// representations of the arg string 
char *makeHexStringFromCharString(const char*); 
// 
// allocates space for about 1/2 strlen(arg) 
// and fills it with the char representation 
char *makeCharStringFromHexString(const char*); 


// this is just sample code 
int main() { 
    char source[256]; 
    printf("Enter a Char string to convert to Hex:"); 
    scanf("%s", source); 
    char *output = makeHexStringFromCharString(source); 
    printf("converted '%s' TO: %s\n\n", source, output); 
    free(output); 
    printf("Enter a Hex string to convert to Char:"); 
    scanf("%s", source); 
    output = makeCharStringFromHexString(source); 
    printf("converted '%s' TO: %s\n\n", source, output); 
    free(output); 
} 


// Place these in a .c file (named same as .h above) 
// and include it in your target's build settings 
// (should happen by default if you create the file in Xcode) 
char *makeHexStringFromCharString(const char*input) { 
    char *output = malloc(sizeof(char) * strlen(input) * 2 + 1); 
    int i, limit; 
    for(i=0, limit = strlen(input); i<limit; i++) { 
     sprintf(output + (i*2), "%x", input[i]); 
    } 
    output[strlen(input)*2] = '\0'; 
    return output; 
} 

char *makeCharStringFromHexString(const char*input) { 
    char *output = malloc(sizeof(char) * (strlen(input)/2) + 1); 
    char sourceSnippet[3] = {[2]='\0'}; 
    int i, limit; 
    for(i=0, limit = strlen(input); i<limit; i+=2) { 
     sourceSnippet[0] = input[i]; 
     sourceSnippet[1] = input[i+1]; 
     sscanf(sourceSnippet, "%x", (int *) (output + (i/2))); 
    } 
    output[strlen(input)/2+1] = '\0'; 
    return output; 
} 
相關問題