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

995 Views Asked by At

If been trying to figure this out for ages now and my mind is gone to mush.

What I want to do is store a hex value in NSData in a plist. I then want to be able to read the hex back out.

I have gotten very confused.

So I try to store the hex value 0x1124. When I look in the plist that gets made the value says 24110000. And When I print this value I get 23FA0

What I want to be able to do is confirm that 0x1124 gets written to my plist and make sure I can print back out the right value.

Im getting the feeling that Im lacking some very fundamental stuff here.

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

There are 2 best solutions below

0
On BEST ANSWER

0x1124 is just a hex representation of the binary bits 0001000100100100 or decimal number 4388. The 0x is just a way to designate the base of the display, it is not part of the number. The number could be expressed in a program in binary with a 0b prefix: int b = 0b0001000100100100;. These are all just different representations of the same number.

To add a number to a NSDictionary or NSArray you need to convert it to an NSNumber, the easiest way is to use literal syntax: @(0x1124) or @(4388).

Ex:

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

or

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

If you want to store only two bytes use an explicit UInt16 type

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