NSData+Conversion.m 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. //
  2. // NSData+Conversion.m
  3. // GlucoseLink
  4. //
  5. // Created by Pete Schwamb on 8/5/14.
  6. // Copyright (c) 2014 Pete Schwamb. All rights reserved.
  7. //
  8. #import "NSData+Conversion.h"
  9. @implementation NSData (Conversion)
  10. - (NSString *)hexadecimalString {
  11. /* Returns hexadecimal string of NSData. Empty string if data is empty. */
  12. const unsigned char *dataBuffer = (const unsigned char *)self.bytes;
  13. if (!dataBuffer)
  14. return [NSString string];
  15. NSUInteger dataLength = self.length;
  16. NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
  17. for (int i = 0; i < dataLength; ++i)
  18. [hexString appendString:[NSString stringWithFormat:@"%02lx", (unsigned long)dataBuffer[i]]];
  19. return [NSString stringWithString:hexString];
  20. }
  21. + (NSData*)dataWithHexadecimalString: (NSString*)hexStr
  22. {
  23. NSMutableData *data = [[NSMutableData alloc] init];
  24. unsigned char whole_byte;
  25. char byte_chars[3] = {'\0','\0','\0'};
  26. for (int i = 0; i < (hexStr.length / 2); i++) {
  27. byte_chars[0] = [hexStr characterAtIndex:i*2];
  28. byte_chars[1] = [hexStr characterAtIndex:i*2+1];
  29. whole_byte = strtol(byte_chars, NULL, 16);
  30. [data appendBytes:&whole_byte length:1];
  31. }
  32. return data;
  33. }
  34. @end