Print NSData into Hex format
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
// | |
// NSData+HexString.swift | |
// Cybertk | |
// | |
// Created by Quanlong He on 8/14/15. | |
// Copyright © 2015 Quanlong He. All rights reserved. | |
// | |
import Foundation | |
private let kHexChars = Array("0123456789ABCDEF".utf8) as [UInt8] | |
extension NSData { | |
public func hexString() -> String { | |
guard length > 0 else { | |
return "" | |
} | |
let buffer = UnsafeBufferPointer<UInt8>(start: UnsafePointer(bytes), count: length) | |
var output = [UInt8](count: length*2 + 1, repeatedValue: 0) | |
var i: Int = 0 | |
for b in buffer { | |
let h = Int((b & 0xf0) >> 4) | |
let l = Int(b & 0x0f) | |
output[i++] = kHexChars[h] | |
output[i++] = kHexChars[l] | |
} | |
return String.fromCString(UnsafePointer(output))! | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment