0

如果我有一个字符串,如何在 Objective-C 中将值转换为十六进制?同样,如何将十六进制字符串转换为字符串?

4

1 回答 1

1

As an exercise and in case it helps, I wrote a program to demonstrate how I might do this in pure C, which is 100% legal in Objective-C. I used the string-formatting functions in stdio.h to do the actual conversions.

Note that this can (should?) be tweaked for your setting. It will create a string twice as long as the passed-in string when going char->hex (converting 'Z' to '5a' for instance), and a string half as long going the other way.

I wrote this code in such a way that you can simply copy/paste and then compile/run to play around with it. Here is my sample output:

enter image description here

My favorite way to include C in XCode is to make a .h file with the function declarations separate from the .c file with implementation. See the comments:

#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;
}
于 2012-08-09T06:35:19.477 回答