0

Possible Duplicate:
Convert NSString to ASCII Binary Equivilent (and then back to an NSString again)

I would like to know how I can get a character and convert it to binary string.

Let's say I have a string :

NSString* test = @"Test";

How can I print this string as an ASCII binary codes for each character in order from left to right:

T = decimal 84 = binary 1010100
e = decimal 101= binary 1100101

I then want to print the sum sequence of all character codes

NSString binaryTest = @"10101001100101...";
Community
  • 1
  • 1
Alex Stone
  • 46,408
  • 55
  • 231
  • 407
  • I don't understand how the first paragraph relates to the rest of the question. How would you use the binary representation to control animated fading? – jrturton Nov 22 '11 at 18:37
  • 3
    Google is your friend: http://stackoverflow.com/questions/5490347/convert-nsstring-to-ascii-binary-equivilent-and-then-back-to-an-nsstring-again – matt Nov 22 '11 at 18:39
  • I've removed the first paragraph to prevent confusion. The control is called flip flop. Binary lets me control the initial state without having to change multiple bool variables by hand. Fade animation is done by assigning view.alpha= bool?1:0 – Alex Stone Nov 22 '11 at 18:47

1 Answers1

2

This should do what you want:

    NSMutableString *finalString = [[NSMutableString alloc] init];
    NSMutableString *binary;
    NSMutableString *binaryReversed;

    // The original string
    NSString *test = @"Test";

    char temp;
    int i, j, digit, dec;

    // Loop through all the letters in the original string
    for (i = 0; i < test.length; i++) {
        // Get the character
        temp = [test characterAtIndex:i];
        dec = (int)temp;
        binary = [[NSMutableString alloc] initWithString:@""];
        // Convert the decimal value to binary representation
        // getting the remainders and storing them in an NSString
        while (dec != 0) {
            digit = dec % 2;
            dec = dec / 2;
            [binary appendFormat:@"%d", digit];
        }
        // Reverse the bit sequence in the NSString
        binaryReversed = [[NSMutableString alloc] initWithString:@""];
        for (j = (int)(binary.length) - 1; j >= 0; j--) {
            [binaryReversed appendFormat:@"%C", [binary characterAtIndex:j]];
        }
        // Append the bit sequence to the current letter to the final string
        [finalString appendString:binaryReversed];
        [binaryReversed release];
        [binary release];
    }
    // Just show off the result and release the finalString
    NSLog(@"%@ in binary: %@", test, finalString);
    [finalString release];