Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Last active July 14, 2018 12:44
Show Gist options
  • Select an option

  • Save kristopherjohnson/ed2623e1b486a8262b12 to your computer and use it in GitHub Desktop.

Select an option

Save kristopherjohnson/ed2623e1b486a8262b12 to your computer and use it in GitHub Desktop.
Convert NSData bytes to hexadecimal string
import Foundation
extension NSData {
/// Return hexadecimal string representation of NSData bytes
@objc(kdj_hexadecimalString)
public var hexadecimalString: NSString {
let buffer = malloc(UInt(length))
getBytes(buffer, length: length)
let byteArray = UnsafePointer<UInt8>(buffer)
var hexString: NSMutableString = NSMutableString()
for i in 0..<length {
let byte: UInt8 = byteArray[i]
hexString.appendFormat("%02x", UInt(byte))
}
free(buffer)
return NSString(string: hexString)
}
}
@ast
Copy link

ast commented Jun 14, 2015

let bytes = UnsafePointer<UInt8>(self.bytes)

It's not necessary to copy the bytes.

@onmyway133
Copy link

@ast UnsafePointer does not conform to SequenceType

@stklieme
Copy link

Or simply with one line return self.map{ String(format: "%02x", $0) }.joined()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment