将NSString转换为ASCII二进制等效项(然后再次返回到NSString) [英] Convert NSString to ASCII Binary Equivilent (and then back to an NSString again)

查看:146
本文介绍了将NSString转换为ASCII二进制等效项(然后再次返回到NSString)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此有一些疑问.

我想获取一个NSString并将其转换为仅包含0.1值的整数数组,该值表示一个ascii字符串的二进制等效项.

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.

例如说我有以下内容

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

我想以数组结尾

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

然后假设我有二进制整数数组,如何返回到NSString?

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

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

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

将我的字符串转换为ascii,但是我仍然遇到很多问题.有人可以帮我吗? :)

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

推荐答案

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

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

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

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

这篇关于将NSString转换为ASCII二进制等效项(然后再次返回到NSString)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆