Skip to content

jmah/NSData-FastHex

Repository files navigation

NSData+FastHex

Version License Platform

Description

NSData+FastHex adds a category on NSData to convert to and from a hexadecimal string representation. As the name implies, it has a focus on performance, without sacrificing code clarity.

Other implementations found online perform multiple message sends per byte and make additional copies of data buffers, which is wasteful.

Optimization techniques

  • CFStringInlineBuffer for efficient character access (fast enumeration of string characters)
  • -[NSData enumerateByteRangesUsingBlock:] to avoid an extra copy of the NSData buffer if the data isn't contiguous
  • -initWithBytesNoCopy:… to avoid an extra copy of the encoded and decoded data and string buffers

Usage

Objective-C

#import "NSData+FastHex.h"
uint8_t bytes[] = {0xDE, 0xAD, 0xBE, 0xEF, 0x42};
NSData *data = [NSData dataWithBytes:bytes length:sizeof(bytes)];
NSString *hexString = [data hexStringRepresentation]; // => @"DEADBEEF42"
NSData *decoded = [NSData dataWithHexString:hexString];

Swift

var bytes: [UInt8] = [0xDE, 0xAD, 0xBE, 0xEF, 0x42]
var data = NSData(bytes: bytes, length: bytes.count)
var hexString = data.hexStringRepresentation() // => "DEADBEEF42"
var decoded = NSData(hexString: hexString)

Installation

NSData+FastHex is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod "NSData+FastHex"

Author

Jonathon Mah, me@JonathonMah.com

License

NSData+FastHex is available under the MIT license. See the LICENSE file for more info.

About

Fast hexadecimal string encoding / decoding for NSData

Resources

License

Stars

Watchers

Forks

Packages

No packages published