Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Last active July 14, 2018 12:44
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kristopherjohnson/ed2623e1b486a8262b12 to your computer and use it in GitHub Desktop.
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 {
var bytes = [UInt8](count: length, repeatedValue: 0)
getBytes(&bytes, length: length)
let hexString = NSMutableString()
for byte in bytes {
hexString.appendFormat("%02x", UInt(byte))
}
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