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 as
*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.
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;
}