Last active
August 28, 2015 19:30
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) })) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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