【问题标题】:How to Store a Hex Value in a Plist and read in back out again如何在 Plist 中存储十六进制值并再次读入
【发布时间】:2015-09-13 10:40:59
【问题描述】:

如果我已经想了很久,但我的脑子已经糊涂了。

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

我很困惑。

所以我尝试存储十六进制值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];

【问题讨论】:

  • 我想要做的就是在 plist 中存储一个十六进制值,以便我可以作为参数值加载回接受十六进制值的 IOBluetooth。在我的例子中,函数期望的十六进制值是 0x1124。
  • 您需要对数字成为十六进制值的含义进行一些研究。提示:十六进制只是一个数字的显示格式,与十六进制显示的一样:1124,二进制:0001000100100100或十进制:4388。它们都是相同的数字。

标签: objective-c hex plist


【解决方案1】:

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

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

例如:

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

或

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-07
      • 1970-01-01
      • 2015-12-25
      • 1970-01-01
      • 1970-01-01
      • 2014-01-04
      • 2016-06-10
      • 2018-09-12
      相关资源
      最近更新 更多