【问题标题】:Convert NSString to ASCII Binary Equivilent (and then back to an NSString again)将 NSString 转换为 ASCII Binary Equivilent(然后再次转换回 NSString)
【发布时间】:2011-03-30 18:10:12
【问题描述】:

我遇到了一些问题。

我想获取一个 NSString 并将其转换为仅包含 0,1 个值的整数数组,该值将表示 ascii 字符串的二进制等价物。

例如说我有以下内容

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

我想以数组结束

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

那么鉴于我有二进制整数数组,我该如何返回 NSString?

我知道 NSString 将字符存储为多个字节,但我只想使用 ASCII。 我试过用,

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

将我的字符串转换为ASCII,但我仍然有很多问题。有人可以帮我吗? :)

【问题讨论】:

标签: objective-c iphone-sdk-3.0 binary nsstring


【解决方案1】:

*请注意,此代码省略了将位存储到整数数组中的额外要求,以便于理解。

// 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);

现在我想我必须在执行这些步骤之前从我的 NSString 中过滤掉所有非 ascii 字符。

【讨论】:

    【解决方案2】:

    将 NSString 转换为整数:(从 Ben 发布的链接中获得)

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

    然后将其传递给下面的函数:

    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;
    }
    

    【讨论】:

    • 这不太奏效,因为它提取了整数的所有 32 位。但是你的代码让我思考。我已经在下面发布了最终为我工作的内容。感谢您朝着正确的方向前进!
    猜你喜欢
    • 2011-04-24
    • 2015-10-30
    • 2014-08-12
    • 1970-01-01
    • 1970-01-01
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    • 2011-10-08
    相关资源
    最近更新 更多