如果我有一个字符串,如何在Objective-C中将值转换为十六进制?同样,我如何从十六进制字符串转换为字符串?
答案 0 :(得分:1)
作为一项练习,如果它有所帮助,我写了一个程序来演示如何在纯C中实现这一点,这在Objective-C中是100%合法的。我使用stdio.h中的字符串格式化函数来进行实际转换。
请注意,这可以(应该?)为您的设置进行调整。它将创建一个字符串,当传入char-> hex(例如将'Z'转换为'5a')时,传入字符串的长度是传递的字符串的两倍,而字符串的长度则是另一半。
我用这样的方式编写了这段代码,你可以简单地复制/粘贴然后编译/运行来玩它。这是我的示例输出:
我最喜欢在XCode中包含C的方法是创建一个.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;
}