Convert NSString to ASCII Binary Equivilent (and t

2019-03-02 06:30发布

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

2条回答
Explosion°爆炸
2楼-- · 2019-03-02 07:03

*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.

查看更多
在下西门庆
3楼-- · 2019-03-02 07:25

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;
}
查看更多
登录 后发表回答