2

My user is prompted to enter in RAW NSData (like: <0201581d 9fc84f7b bf136a80 e7fc9572>)

This raw data is an AES encrypted NSString.

However, the issue is converting those actual bytes of data <0201581d 9fc84f7b bf136a80 e7fc9572> into an NSData type itself.

  1. Prompted to enter data
  2. Enters data --> @"<0201581d 9fc84f7b bf136a80 e7fc9572>"
  3. Needs to make entered data into an NSData type rather than the NSString which was passed.

In short; How do I make this: <0201581d 9fc84f7b bf136a80 e7fc9572> into the NSData's data? Making an integer hold the data HALF works (because the type is too short) so It needs to be an NSString.

evdude100
  • 437
  • 4
  • 18

3 Answers3

3

To convert a hexadecimal string to data, see the function that I posted here: Converting a hexadecimal string into binary in Objective-C

You will want to modify it slightly to allow bracket characters and whitespace.

To go the other direction:

NSString *CreateHexStringWithData(NSData *data)
{
    NSUInteger inLength = [data length];
    unichar *outCharacters = malloc(sizeof(unichar) * (inLength * 2));

    UInt8 *inBytes = (UInt8 *)[data bytes];
    static const char lookup[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    NSUInteger i, o = 0;
    for (i = 0; i < inLength; i++) {
        UInt8 inByte = inBytes[i];
        outCharacters[o++] = lookup[(inByte & 0xF0) >> 4];
        outCharacters[o++] = lookup[(inByte & 0x0F)];
    }

    return [[NSString alloc] initWithCharactersNoCopy:outCharacters length:o freeWhenDone:YES];
}

You can also use:

[NSString stringWithFormat:@"%@", data]

to use -[NSData description] to get a version with the brackets and spaces.

Community
  • 1
  • 1
iccir
  • 5,078
  • 2
  • 22
  • 34
  • This is not what I'm looking for unfortunately. The NSData is encrypted so it's not an actual NSString. I just need to store it to a type. – evdude100 Jan 22 '12 at 15:15
  • I used your conversion, but it's useless without the string converted into actual NSData. Upvoted; But Rob gets the acceptance – evdude100 Jan 22 '12 at 15:26
2

This is extremely similar to NSString (hex) to bytes. The answer there will work for you if you remove the excess punctuation.

Community
  • 1
  • 1
Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • I used a combination of this and iccir's solution. I needed the hex string to use this solution! Thanks! – evdude100 Jan 22 '12 at 15:24
0

To convert NSData to NSString use :

NSData* returnData;
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

To convert NSString to NSData use :

NSString* str = @"returnString";
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Ashwini Chougale
  • 1,093
  • 10
  • 26