When I call -description
on an NSData
object, I see a pretty Hex string of the NSData
object's bytes like:
<f6e7cd28 0fc5b5d4 88f8394b af216506 bc1bba86 4d5b483d>
I'd like to get this representation of the data (minus the lt/gt quotes) into an in-memory NSString
so I can work with it.. I'd prefer not to call -[NSData description]
and then just trim the lt/gt quotes (because I assume that is not a guaranteed aspect of NSData
's public interface and is subject change in the future).
What's the simplest way to get this representation of an NSData
object into an NSString
object (other than calling -description
)?
In Swift you can create an extension.
Then you can simply use:
While it may not be the most efficient way to do it, if you're doing this for debugging, SSCrypto has a category on NSData which contains two methods to do this (one for creating an NSString of the raw byte values, and one which shows a prettier representation of it).
http://www.septicus.com/SSCrypto/trunk/SSCrypto.m
I liked @Erik_Aigner's answer the best. I just refactored it a bit:
Sadly there's no built-in way to produce hex from an NSData, but it's pretty easy to do yourself. The simple way is to just pass successive bytes into sprintf("%02x") and accumulate those into an NSMutableString. A faster way would be to build a lookup table that maps 4 bits into a hex character, and then pass successive nybbles into that table.
Seeing there is a Swift 1.2 snippet in the comments, here's the Swift 2 version since C style for loops are deprecated now. Gist with MIT license and two simple unit tests if you care.
Here's the code for your convenience:
Keep in mind that any
String(format: ...)
solution will be terribly slow (for large data)If you need something more performant try this:
Swift 4.2 version