lreichold
lreichold

Reputation: 765

Convert "String" of Binary to NSString of text

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.

Upvotes: 2

Views: 2134

Answers (2)

Simon Whitaker
Simon Whitaker

Reputation: 20566

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. :-))

Upvotes: 1

sidyll
sidyll

Reputation: 59287

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.

Upvotes: 2

Related Questions