Tommaso Piazza

It is sometimes useful to get a hexadecimal string representation of the contents of NSData just the way they are stored in memory.
This is the case, for example, when you want to communicate to your backend service the value of the push token assigned to your device by
Apple’s Push Notifications Services.

If your push token is stored in memory as 0xDEADBEEF, then the string “deadbeef” is exactly what you
want to send to your backend service.

This is simply done as follows:

funcdataToHexString(data:NSData)->String{letpointer=UnsafePointer<UInt8>(data.bytes)letcount=data.length// Get our buffer pointer and make an array out of itletbuffer=UnsafeBufferPointer<UInt8>(start:pointer,count:count)letarray=[UInt8](buffer)letpushToken=reduce(array,""){(s:String,int:UInt8)->Stringinletchars=String(format:"%02x",int)returns.stringByAppendingString(String(chars))}returnpushToken}letd=NSData(bytes:[0xDE,0xAD,0xBE,0xEF]as[UInt8],length:4)letc=dataToHexString(d)// deadbeef

If you are looking instead for how to make a string out of NSData, that is simply done by using the correct NSString initializer.