Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Print NSData into Hex format
//
// 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