Convert “String” of Binary to NSString of text

和自甴很熟 提交于 2019-12-24 02:04:25

问题


I am able to convert an NSString of (ASCII) text to a NSString of binary numbers, but I am having troubles doing the opposite. For example: "Hi" becomes "01101000 01101001".

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

I'm looking for the most direct way to implement this. Note the space between every 8 bits of binary numbers.


回答1:


Considering the format is always like that, this code should work:

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];
}

Tell me if some part of it was unclear.




回答2:


How's this?

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;
}

(Posting as a community wiki - my old-skool C skills are dead rusty - feel free to clean this up. :-))



来源:https://stackoverflow.com/questions/6496561/convert-string-of-binary-to-nsstring-of-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!