2012-08-09 99 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; 
} 
相关问题