Python打包/解包转换为Objective C

2024-10-03 17:28:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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

输出

^{pr2}$

我在objective C中进行了第一次int数组转换,但仍停留在打包和解包上

第一部分目标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的工作方式。在


Tags: in脚本fordatapacklistintprint
1条回答
网友
1楼 · 发布于 2024-10-03 17:28:20

我想说的是,我应该先在a-C水平上学习。Python都是动态生成的,因为这两种语言都不是动态类型的。不过,我会给你一些建议

让我们更深入地了解一下您的代码:

A

你有:

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

我真的看不出把所有数字都转换成字符串有什么好处。只需储存号码:

^{pr2}$

@[]表示“数组文本”,@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

您可以用-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 );

如果您真的需要将值存储为字符串,请告诉我。我会修改我的答案。在

相关问题 更多 >