开发者

Map NSString characters to NSData(hex)?

if i have a NSString as @"aef1230fe" how can I map it to NSData exacaly so that when doing this:

NSLog("%@",开发者_开发知识库mydata); 

gives me the output: <aef1230fe>


Unshifting and shifting.

Step one: Get the byte string from your NSString, this is achieved using -UTF8String.

Step two: Read each character in the string, mapping them to their corresponding quartet:

for (char *iterator = myByteString; *iterator != '\0'; iterator++) {
  switch *iterator {
  case 0:
    quartet = 0x00;
    break;
  case 1:
    quartet = 0x01;
    break;
  /// .... Optimizations exists
  }
}

Step three: Shift your quartet up every second time, and or it with the other one:

octet = quartet1 << 4 | quartet2;

Step four: Stick your new octet in a buffer to hold the data (this buffer should be malloced to [dataString length] / 2).

Step five: Turn the buffer into an NSData object.

As mentioned in the comment above, optimizations exist for the switch; namely the use of quartet = *iterator - 'a' (or '0', or 'A', depending on what segment of the switch you are in).

Of course, you might be able to finagle something using the property list serialization API as well (or rather, deserialization).


Or You could do it like this

NSString *string = @"aef1230f";

const char * bytes = [string cStringUsingEncoding: NSUTF8StringEncoding];
NSUInteger length = strlen(bytes);
unsigned char * r = (unsigned char *) malloc(length / 2 + 1);
unsigned char * index = r;

while ((*bytes) && (*(bytes +1))) {
    *index = strToChar(*bytes, *(bytes +1));
    index++;
    bytes+=2;
}
*index = '\0';

NSData *dataFromString = [NSData dataWithBytes: r length: length / 2];
free(r);

NSLog(@"Hex data from hex string: %@", dataFromString);

Function strToChar should look like this:

unsigned char strToChar (char a, char b) {
char encoder[3] = {'\0','\0','\0'};
encoder[0] = a;
encoder[1] = b;
return (char) strtol(encoder,NULL,16); }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜