0

I need to parse an NSString to a byte array and am having some trouble doing it. I have a padded byte array in a method and convert that into a mutablestring, then I have a method that needs to place those numbers back into a byte array. In C# it would be as simple as:

do
{
    val = byte.Parse(str.Substring(i, 3));
    byteArr[j++] = val;
    i += 3;
}

Here is the code snippit Note** Ive been trying a lot of different things in the do loop so its a mess in there right now:

-(NSData*) StrToByteArray: (NSString*)str 
{
    NSLog(@"StrToByteArray. String: %@", str);
    if([str length]==0)
       NSLog(@"Invailid String");
    int val;
    Byte byteArr[[str length]/3];
    int i = 0;
    int j = 0;
    NSRange range; 
    do {
       range = NSMakeRange(i, 3);
       val = (int)[str substringFromIndex:i];
       NSLog(@"StrToByteArray. VAR: %i", val);
       byteArr[j++] = val;
       NSLog(@"byteArr: %i",byteArr[i]);
       i+=3;
    }while(i<str.length);
    NSData* wrappedByteArr = [NSData dataWithBytes:&byteArr length: sizeof(byteArr)];
    return wrappedByteArr;
}

Here is the loop that makes the padded string:

for(int i = 0; i<=len;i++)
{
    val = byteArr[i];
    NSLog(@"byteArr to string original: %i", val);
    if(val<(Byte)10)
    {
        [tempStr appendString:(@"00")];
        [tempStr appendString:[NSString stringWithFormat:@"%d",val]];
    }
    else if(val<(Byte)100)
    {
        [tempStr appendString:(@"0")];
        [tempStr appendString:[NSString stringWithFormat:@"%d",val]];
    }
    else {

        [tempStr appendString:[NSString stringWithFormat:@"%d",val]];
    }

}
NSLog(@"string: %@", tempStr);
return tempStr;
4

1 に答える 1

1

テイク 2

データがどのように見え、どのように解析したいかがわかったので、次のようにアプローチします。

- (NSData *) parseStringToData:(NSString *) str
{
    if ([str length] % 3 != 0)
    {
        // raise an exception, because the string's length should be a multiple of 3.
    }

    NSMutableData *result = [NSMutableData dataWithLength:[str length] / 3];
    unsigned char *buffer = [result mutableBytes];

    for (NSUInteger i = 0; i < [result length]; i++)
    {
        NSString *byteString = [str substringWithRange:NSMakeRange(i * 3, 3)];
        buffer[i] = [byteString intValue];
    }

    return result;
}

編集:

整数を自動的にパディングする正しいフォーマット指定子を提供することで、パディング方法も簡素化できます。

for(int i = 0; i<=len;i++)
{
    val = byteArr[i];
    NSLog(@"byteArr to string original: %i", val);

    [tempStr appendFormat:@"%03d", val];
}
于 2013-01-17T06:31:00.230 に答える