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

后端 未结 2 2024
囚心锁ツ
囚心锁ツ 2021-01-26 19:06

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

相关标签:
2条回答
  • 2021-01-26 19:35

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

    0 讨论(0)
  • 2021-01-26 19:36

    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;
    }
    
    0 讨论(0)
提交回复
热议问题