将Binary的“String”转换为文本的NSString

时间:2011-06-27 17:26:58

标签: iphone objective-c binary nsstring ascii

我能够将(ASCII)文本的NSString转换为二进制数的NSString,但是我遇到了相反的麻烦。例如:“Hi”变为“01101000 01101001”。

I need: "01101000 01101001" to become "Hi".

我正在寻找最实现直接的方法。注意每8位二进制数之间的空格。

2 个答案:

答案 0 :(得分:2)

考虑到格式始终,这段代码应该有效:

NSString *
BinaryToAsciiString (NSString *string)
{
    NSMutableString *result = [NSMutableString string];
    const char *b_str = [string cStringUsingEncoding:NSASCIIStringEncoding];
    char c;
    int i = 0; /* index, used for iterating on the string */
    int p = 7; /* power index, iterating over a byte, 2^p */
    int d = 0; /* the result character */
    while ((c = b_str[i])) { /* get a char */
        if (c == ' ') { /* if it's a space, save the char + reset indexes */
            [result appendFormat:@"%c", d];
            p = 7; d = 0;
        } else { /* else add its value to d and decrement
                  * p for the next iteration */
            if (c == '1') d += pow(2, p);
            --p;
        }
        ++i;
    } [result appendFormat:@"%c", d]; /* this saves the last byte */

    return [NSString stringWithString:result];
}

告诉我它的某些部分是否不清楚。

答案 1 :(得分:1)

这是怎么回事?

NSString* stringFromBinString(NSString* binString) {
    NSArray *tokens = [binString componentsSeparatedByString:@" "];
    char *chars = malloc(sizeof(char) * ([tokens count] + 1));

    for (int i = 0; i < [tokens count]; i++) {
        const char *token_c = [[tokens objectAtIndex:i] cStringUsingEncoding:NSUTF8StringEncoding];
        char val = (char)strtol(token_c, NULL, 2);
        chars[i] = val;
    }
    chars[[tokens count]] = 0;
    NSString *result = [NSString stringWithCString:chars 
                                          encoding:NSUTF8StringEncoding];

    free(chars);
    return result;
}

(作为社区维基发布 - 我的旧技能C技能已经生锈 - 随意清理它。: - ))