Python 打包/解包转换为 Objective C

Python pack / unpack converts to Objective C

我有一个 Python 脚本,我想在 objective C 中转换。

from struct import *
data = [10000,10000,10000,10]
d = [int(i) for i in data]
print d
list = unpack('BBBBBBBBBBBBBBBB',pack('>IIII', d[0], d[1], d[2], d[3]))
print list

输出

[10000, 10000, 10000, 10]
(0, 0, 39, 16, 0, 0, 39, 16, 0, 0, 39, 16, 0, 0, 0, 10)

我在 objective C 中完成了第一个 int 数组转换,但卡在打包和解包

Objective C 第一部分

NSArray *timouts = [NSArray arrayWithObjects:[NSString stringWithFormat:@"10000"],[NSString stringWithFormat:@"10000"],[NSString stringWithFormat:@"10000"],[NSString stringWithFormat:@"10"],nil];

    NSMutableArray *ary = [NSMutableArray arrayWithCapacity:4];
    NSInteger coutner = 0;
    for (NSString *string in timouts)
    {
        int outVal;
        NSScanner* scanner = [NSScanner scannerWithString:string];
        [scanner scanInt:&outVal];

        ary[coutner] = [NSString stringWithFormat:@"%d",outVal];
        coutner++;
    }

我曾尝试这样做,但对 Python 脚本编写不太了解。不了解 packunpack 的工作方式。

首先我想说的是你应该尝试在更好的水平上学习Objective-C。这并不太难(尤其是来自 Python,因为这两种语言都是动态类型的)。但是,我会给你一些建议给你的问题。

让我们仔细看看您的代码:

A.

你有:

NSArray *timouts = [NSArray arrayWithObjects:[NSString stringWithFormat:@"10000"],[NSString stringWithFormat:@"10000"],[NSString stringWithFormat:@"10000"],[NSString stringWithFormat:@"10"],nil];

我真的没有看到将所有数字转换为字符串有任何好处。只需存储数字:

NSArray *timeOuts = @[@10000, @10000, @10000, @10];

@[]表示"array literal",@x表示NSNumber实例对象。

B.

您可以简单地使用 NSLog():

打印列表本身
NSLog( @"%@", timeOuts );

C。

您必须读取 NSNumber 的实例,因为您存储了这样的实例:

NSMutableArray * bytes = [NSMutableArray arrayWithCapacity:4];
for (NSNumber *value in timeOuts) // Take out numbers
{
…
}

D.

现在是最难的部分:拆包

因为您将 NSNumber 的实例存储到数组中,所以很容易获得整数值:

NSMutableArray *bytes = [NSMutableArray arrayWithCapacity:4];
for (NSNumber *value in timeOuts) // Take out numbers
{
   int intValue = [value intValue];
   …
}

E.

你可以"pack them"变成一个字符串-stringWithFormat:。但是,如果我理解你 Q 中的日志是正确的,你想打印出一个值的单个字节,而不是整个值。

NSMutableArray *bytes = [NSMutableArray arrayWithCapacity:4];
for (NSNumber *value in timeOuts) // Take out numbers
{
   int intValue = [value intValue];
   for( int x = 0; x < 4; x++ )
   {
     int byte = intValue & 0xFF000000; // Mask out bit 0-23
     [bytes addObject:@(byte)];  // Store byte
     intValue <<= 8;             // Shift up bit 0-23 to 8-31 for the next iteration

   }
}
NSLog( @"%@", bytes );

z.

所以我们最终得到这个:

NSArray *timeOuts = @[@10000, @10000, @10000, @10];
NSLog( @"%@", timeOuts );

NSMutableArray *bytes = [NSMutableArray arrayWithCapacity:4];
for (NSNumber *value in timeOuts) // Take out numbers
{
   int intValue = [value intValue];
   for( int x = 0; x < 4; x++ )
   {
     int byte = intValue & 0xFF; // Mask out bit 8-31
     [bytes addObject:@(byte)];  // Store byte
     intValue >>= 8;             // Shift down bit 8-31 to 0-23 for the next iteration

   }
}
NSLog( @"%@", bytes );

如果您确实需要将值存储为字符串,请告诉我。我会编辑我的答案。