gpt4 book ai didi

Cocoa 将八进制的 NSArray/NSString 转换为 NSData?

转载 作者:行者123 更新时间:2023-12-03 18:02:11 24 4
gpt4 key购买 nike

我正在尝试将这段 C 代码转换为 Cocoa,但我正在努力弄清楚如何实现。

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

我尝试过使用 NSMutableArray 和 NSData 但没有运气。我能够扫描字符串并提取数字,但我不知道之后如何存储到 NSData 中。

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

基本上尝试将 ascii DES key 转换为字符串以用于三重 DES 加密。非常感谢任何帮助,谢谢!

最佳答案

@Keenan“我希望避免使用 sscanf 和 char* 代替 Cocoa 类”。好吧,你可以做到这一点,但是你希望生产什么?如果您想要一个字节数组作为结果,那么您需要坚持使用unsigned char[],这就引出了为什么要在上进行解析的问题首先是 NSString

这是您的 C 代码的 Objective-C 翻译。请注意,八进制被 Cocoa 视为古老的历史,因此它的解析类仅处理十进制和十六进制,因此您需要编写自己的或使用标准 C 函数(下面的 strtol)。

此示例同时生成一个 unsigned char[] 和一个 NSMutableArray - 选择一个。

// There are no checks in the code, like in the original...
// BTW 789 is not an octal number...
NSString *descKey = @"123 456 789 101 112 131 415 161"; // char *deskey = "123 456 789 101 112 131 415 161";
// pick one...
NSMutableArray *keyObjC = [NSMutableArray new]; // unsigned char key[16];
unsigned char keyC[16];
// memset(key, 0, sizeof(key));

// As @JeremyP has pointed out the sscanf is wrong as %o produces a 4-byte value and you only want a 1-byte one.
// In C you would therefore need key to be an array of ints and then assign each element to a byte (unsigned char),
// or parse a different way.

unsigned ix = 0; // for keyC choice only
NSArray *numbers = [descKey componentsSeparatedByString:@" "]; // sscanf(deskey, "%o %o %o %o %o %o %o %o",
for (NSString *aNumber in numbers) // (int*)&key[0], (int*)&key[1], (int*)&key[2],
{ // (int*)&key[3], (int*)&key[4], (int*)&key[5],
// (int*)&key[6], (int*)&key[7]);
unsigned char next = (unsigned char)strtol([aNumber UTF8String], NULL, 8);
keyC[ix++] = next; // for keyC choice
[keyObjC addObject:[NSNumber numberWithUnsignedChar:next]]; // keyObjC choice
}

如果你想接近 Python 的一行,只需将迭代压缩为:

for (NSString *aNumber in [descKey componentsSeparatedByString:@" "]) { [keyObjC addObject:[NSNumber numberWithUnsignedChar:(unsigned char)strtol([aNumber UTF8String], NULL, 8)]]; }

但当然还更长!

关于Cocoa 将八进制的 NSArray/NSString 转换为 NSData?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5274927/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com