I’m trying to covert this bit of C code to Cocoa and I’m struggling to figure out how.
char *deskey = "123 456 789 101 112 131 415 161";
unsigned char key[16];
memset(key, 0, sizeof(key));
sscanf(deskey, "%o %o %o %o %o %o %o %o",
(int*)&key[0], (int*)&key[1], (int*)&key[2],
(int*)&key[3], (int*)&key[4], (int*)&key[5],
(int*)&key[6], (int*)&key[7]);
I’ve tried using NSMutableArray and NSData but having no luck. I was able to scan the string and pull out the numbers, but I’m not sure how to store into NSData after that.
NSMutableArray *enckey = [[[NSMutableArray alloc] init] autorelease];
NSScanner *scanner = [NSScanner scannerWithString:self.deskey];
int pos = 0;
while ([scanner isAtEnd] == NO) {
if ([scanner scanInt:&pos]) {
[enckey addObject:[NSString stringWithFormat:@"%o", pos]];
}
else {
NSLog(@"Your DES key appears to be invalid.");
return;
}
}
Basically trying to convert ascii DES key to string to use for Triple DES encryption. Any help is greatly appreciated, thank you!
@Keenan “I was hoping to avoid using sscanf and char* in place of the Cocoa classes”. Well you can do that, but what are you hoping to produce? If you want a byte array as the result then you need to stick to
unsigned char[], and that begs the question why you’d do the parsing onNSStringin the first place.Here is an Objective-C translation of your C code. Note that octal is seen as ancient history by Cocoa so its parsing classes only deal with decimal and hexadecimal, so you need to write your own or use a standard C function (
strtolbelow).This example produces both a
unsigned char[]and anNSMutableArray– pick one.If you want to approach the one line of your Python just compress the iteration to:
but it is still longer of course!