NSString to NSData conversion to Hex Value [duplic

2019-09-02 04:19发布

问题:

This question already has an answer here:

  • Converting HEX NSString To NSData 4 answers

I've been trying to convert a user defaults NSString (tried NSData also), into a hex value I can use with char array. the problem is that every time I convert it from the NSString or NSData it takes the hex values and turns them into ASCII values, which isn't what I want at all. how to I tell it to literally take the values that are there and keep them hex? I'm struggling to find a solution.

inside my .plist

<key>shit</key>
<string>5448495344414e475448494e474e45454453544f53544159484558</string>

my code to convert the NSString to NSData

  NSString *defaults = [[NSUserDefaults standardUserDefaults] objectForKey:@"shit"];
    NSData *theData = [defaults dataUsingEncoding:NSUTF8StringEncoding];
    NSUInteger dataLength = [theData length];
    Byte *byteData = (Byte*)malloc(dataLength);
    memcpy(byteData, [theData bytes], len);

NSLog(@"THIS : %@",[NSData dataWithBytes:byteData length:len]);

output:

THIS : <35343438 34393533 34343431 34653437 35343438 34393465 34373465 34353435 34343533 35343466 35333534 34>len

why in the world is it doing this? I want the original hex values, not interpretation of my hex values.

回答1:

A byte is neither hex nor ascii nor octal nor int nor float, etc, they are just different ways to display and/or think about a byte(s). The way NSLog displays objects is dictated by the way the objects's description method is written. Thus NSLog of NSData and NSString display the same bytes differently.

If you want access to the bytes in an NSData just access them directly: theData.bytes, no need tomemcpy`.

Lastly and most importantly: What are you trying to accomplish?

New developers are well served by getting a good book on the "C" language and studying it--that is what I did.



回答2:

This is the method I use to get Hex data from string:

-(NSData *) HexByteDataFromString:(NSString *) str
{
    NSMutableData *data= [[NSMutableData alloc]init];
    unsigned char whole_byte;
    char byte_chars[3] = {'\0','\0','\0'};
    for (int i = 0; i < ([str length] / 2); i++)
    {
        byte_chars[0] = [str characterAtIndex:i*2];
        byte_chars[1] = [str characterAtIndex:i*2+1];
        whole_byte = strtol(byte_chars, NULL, 16);
        [data appendBytes:&whole_byte length:1];
    }
    return data;
}

Now to print the data in NSData, just use this

NSLog(@"%@",[myData description]);

Here, description will give exactly the hex values as you wanted. :)

Update:

Use Byte *dataBytes = (Byte *)[myData bytes]; This will give you the same thing you need. You can refer to particular byte just like you refer them from byte array.

like this:

char x=  dataBytes[2];

Let me know if this is still not solving your problem.. :)