且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

转换"弦乐"二进制到文字的NSString

更新时间:2022-06-13 07:54:12

考虑到格式的总是的那样,这code应该工作:

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.