1

I'm having some problems with this.

I want to take an NSString and convert it to an integer array of only 0,1 values that would represent the binary equivalent of an ascii string.

So for example say I have the following

NSString *string = @"A"; // Decimal value 65

I want to end up with the array

int binary[8] = {0,1,0,0,0,0,0,1};

then given that I have the binary integer array, how do I go back to an NSString?

I know that NSString stores characters as multiple bytes but I only want to use ASCII. I tried using,

NSData *data = [myString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

to convert my string to ascii, but I'm still having a lot of issues. Can someone please help me out? :)

Ben Holland
  • 2,309
  • 4
  • 34
  • 50
  • I'm thinking this post, along with some bit shifting and masking might do the trick, but then I'm still not sure how to convert the NSString to only ascii characters first. http://stackoverflow.com/questions/2832729/how-to-convert-ascii-value-to-a-character-in-objective-c – Ben Holland Mar 30 '11 at 19:33

2 Answers2

3

*Note this code leaves out the extra requirement of storing the bits into an integer array in order to be easier to understand.

// test embed
NSString *myString = @"A"; //65
for (int i=0; i<[myString length]; i++) {
    int asciiCode = [myString characterAtIndex:i];
    unsigned char character = asciiCode; // this step could probably be combined with the last
    printf("--->%c<---\n", character);
    printf("--->%d<---\n", character);
    // for each bit in a byte extract the bit
    for (int j=0; j < 8; j++) {
        int bit = (character >> j) & 1;
        printf("%d ", bit);
    }           
}


// test extraction
int extractedPayload[8] = {1,0,0,0,0,0,1,0}; // A (note the byte order is backwards from conventional ordering)
unsigned char retrievedByte = 0;

for (int i=0; i<8; i++) {
    retrievedByte += extractedPayload[i] << i;
}

printf("***%c***\n", retrievedByte);
printf("***%d***\n", retrievedByte);

Now I guess I've just got to filter out any non ascii characters from my NSString before I do these steps.

Ben Holland
  • 2,309
  • 4
  • 34
  • 50
2

Convert NSString to Integer:(got it from link Ben posted )

// NSString to ASCII
NSString *string = @"A";
int asciiCode = [string characterAtIndex:0]; // 65

then pass it to function below :

NSArray *arrayOfBinaryNumbers(int val) 
{
    NSMutableArray* result = [NSMutableArray array];
    size_t i;
    for (i=0; i < CHAR_BIT * sizeof val; i++) {
        int theBit = (val >> i) & 1;
        [result addObject:[NSNumber numberWithInt:theBit]];
    }
    return result;
}
0x8badf00d
  • 6,391
  • 3
  • 35
  • 68
  • This didn't quite work because it pulls out all 32 bits of the integer. But your code got me thinking. I've posted what ended up working for me below. Thanks for the push in the right direction! – Ben Holland Mar 31 '11 at 00:04