XCode IOS方法从const unsigned char输入数组

时间:2013-03-25 16:04:48

标签: ios arrays function methods initializer

目前我有一些实例方法可以生成一些数据,我想为单个方法更改一些数据,这个方法接受我传递给它的输入,编译器告诉我数组初始值设定项必须是初始化列表或string literal。

我将字符串传递给这样的方法: -

  [self buildrawdata2:(const unsigned char *)"0ORANGE\0"];

这个方法在数组使用字符串设置为“0ORANGE \ 0”时有效,我传递的字符串也从最后缺少“\ 0”,我相信这是因为它是一个控制字符/转义序列,无论如何都要保留它并将其传递给下面硬编码的字符串: -

 - (void)buildrawdata2:(const unsigned char *)inputString2;

 {
     NSLog(@"ViewController::buildrawdata2");
     NSLog(@"ViewController::buildrawdata2 - inputstring2: %s", inputString2);

     //this works when set like this
     const unsigned char magic2[] = "0ORANGE\0";  

     const uint8_t pattern1 = {0xFC};
     const uint8_t pattern2 = {0xE0};

     uint8_t rawdata2[56];
     uint8_t index = 0;

     int byte = 0;
     int bit = 0;

     while (magic2[byte] != 0x00) {

         while (bit < 8) {

        if (magic2[byte] & (1<<bit)) {
            //add pattern2 to the array
            rawdata2[index++] = pattern2;
        }else{
            //add pattern1 to the array
            rawdata2[index++] = pattern1;
        }

        // next bit please
        bit++;
      }

      //next byte please
      byte++;

      //reset bit index
      bit = 0;

      }

      NSLog(@"buildrawdata2::RawData %@", [NSData dataWithBytes:rawdata2 length:56]);

     }

1 个答案:

答案 0 :(得分:0)

看起来我已经找到了解决方案,我很乐意听到其他人对此方法的看法或改进建议。

不是将字符串传递给方法并尝试直接更新数组初始化程序,而是使用字符串来确定应该使用哪个数组初始值设定项。为此,我必须在if块之前创建一个指针,以便我可以在if块中为它分配字符串。

 const unsigned char *magic = NULL;

 if (inputString == @"0APPLES") { magic = (const unsigned char*) "0APPLES\0";}
 else if (inputString == @"0ORANGE") { magic = (const unsigned char*) "0ORANGE\0";}

最近也尝试过这种方式,它也有效: -

 const unsigned char apples[] = "0APPLES\0";
 const unsigned char orange[] = "0ORANGE\0";
 const unsigned char *magic;

 if (inputString2 == @"0APPLES") { magic = apples;}
 else if (inputString2 == @"0ORANGE") { magic = orange;}

然后可以像这样调用该方法: -

 [self buildrawdata1:@"0APPLES"];
 [self buildrawdata1:@"0ORANGE"];