Skip to content

Instantly share code, notes, and snippets.

@CanTheAlmighty
Last active August 28, 2015 19:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CanTheAlmighty/54a0e7c582307e598f4f to your computer and use it in GitHub Desktop.
Save CanTheAlmighty/54a0e7c582307e598f4f to your computer and use it in GitHub Desktop.
Allows to turn NSData into String with the desired encoding, and also provides a convenient way to get an UnsafeBufferPointer from NSData
extension NSData
{
/// Creates a length-delimited, byte buffer
var buffer : UnsafeBufferPointer<UInt8> { get { return UnsafeBufferPointer(start: UnsafePointer<UInt8>(self.bytes), count: self.length) }}
}
extension String
{
/// Initializes a string from the given data
init?(data : NSData, encoding : NSStringEncoding)
{
self.init(bytes: data.buffer, encoding: encoding)
}
/// Initializes a string formatted as an hexadecimal byte array
init(hexData data : NSData, separator: String = ":")
{
self.init(separator.join(map(data.buffer) { return String(format: "%hhX", $0) }))
}
}
import Foundation
let original = "Hello world asdasd asds ddsa as "
let encoding = NSASCIIStringEncoding
if let data = original.dataUsingEncoding(encoding, allowLossyConversion: false)
{
// Turn back into string
String(data: data, encoding: encoding)
// Format as hex values
String(hexData: data, separator: ":")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment