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;