如何在 Plist 中存储十六进制值并再次读入

How to Store a Hex Value in a Plist and read in back out again

如果我想弄清楚这个问题已经很久了,但我的脑子已经乱了。

我想做的是在 plist 的 NSData 中存储一个十六进制值。 然后我希望能够读回十六进制。

我很困惑。

所以我尝试存储十六进制值0x1124。 当我查看生成的 plist 时,值显示 24110000。 当我打印这个值时,我得到 23FA0

我想要做的是确认 0x1124 已写入我的 plist 并确保我可以打印出正确的值。

我觉得我在这里缺少一些非常基本的东西。

NSMutableDictionary  *tempDict=[NSMutableDictionary new];
    // Byte hidService= 1124;
    //int hidService= 00001124-0000-1000-8000-00805f9b34fb
    unsigned int hidService[]={0x1124};

    NSData  *classlist=[NSData dataWithBytes:&hidService length:sizeof(hidService)];
    NSArray  *classListArray=@[classlist];
    [tempDict setValue:classListArray forKey:kServiceItemKeyServiceClassIDList];

    hidProfileDict=[[NSDictionary alloc]initWithDictionary:tempDict];
    NSLog(@"%X",[hidProfileDict valueForKey:kServiceItemKeyServiceClassIDList][0]);


    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSFileManager  *fileManager=[NSFileManager defaultManager];
    NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"HIDDictionary.plist"];
    if (![fileManager fileExistsAtPath: plistPath])
    {
        NSString *bundle = [[NSBundle mainBundle] pathForResource:@"HIDDictionary" ofType:@"plist"];
        [fileManager copyItemAtPath:bundle toPath:plistPath error:&error];
    }
    [hidProfileDict writeToFile:plistPath atomically: YES];

如果只想存储两个字节,请使用显式 UInt16 类型

UInt16 hidService[]={0x1124};
NSData  *classlist = [NSData dataWithBytes:&hidService length:sizeof(hidService)];

0x1124 只是二进制位 0001000100100100 或十进制数 4388 的十六进制表示。0x 只是指定显示基数的一种方式,它不是数字的一部分。该数字可以在带有 0b 前缀的二进制程序中表示:int b = 0b0001000100100100;。这些都是同一个数字的不同表示。

要将数字添加到 NSDictionaryNSArray,您需要将其转换为 NSNumber,最简单的方法是使用文字语法:@(0x1124)@(4388).

例如:

NSArray *a = @[@(0x1124)];

NSDictionary *d = @{kServiceItemKeyServiceClassIDList:@(0x1124)};
// Where kServiceItemKeyServiceClassIDList is defined to be a `NSString`.