Skip to content

Instantly share code, notes, and snippets.

@jpmhouston
Created January 30, 2019 18:20
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 jpmhouston/db1fa96997cef811bc3251b6d50e99d6 to your computer and use it in GitHub Desktop.
Save jpmhouston/db1fa96997cef811bc3251b6d50e99d6 to your computer and use it in GitHub Desktop.
Data extension method hexEncodedString
extension Data {
struct HexEncodingOptions: OptionSet {
let rawValue: Int
static let uppercase = HexEncodingOptions(rawValue: 0)
static let lowercase = HexEncodingOptions(rawValue: 1 << 0)
}
func hexEncodedString(options: HexEncodingOptions = []) -> String {
let hexDigits = Array((options.contains(.lowercase) ? "0123456789abcdef" : "0123456789ABCDEF").utf16)
var dump: [unichar] = []
var ascii: [unichar] = []
dump.reserveCapacity(2 * count + (count + 7)/8 + 70 + ((count + 63)/64) * 35) // div by 8,64 rounding up, 35="| "+ascii+nl, 70=for worstcase 1 byte on last row
ascii.reserveCapacity(32)
var digitCount = 0
for byte in self {
dump.append(hexDigits[Int(byte / 16)])
dump.append(hexDigits[Int(byte % 16)])
ascii.append((isprint(Int32(byte)) != 0) ? unichar(byte) : 46) // "."
digitCount += 2
if digitCount % 8 == 0 {
dump.append(32)
}
if digitCount % 64 == 0 {
dump.append(124) // "|"
dump.append(32)
dump.append(contentsOf: ascii)
dump.append(10) // nl
ascii = []
digitCount = 0
}
}
if digitCount != 0 {
let digits = 64 - digitCount
let separators = (digits + 7) / 8 // div by 8 rounding up
dump.append(contentsOf: Array<unichar>(repeating: 32, count: digits + separators))
dump.append(124) // "|"
dump.append(32)
dump.append(contentsOf: ascii)
dump.append(10) // nl
}
return String(utf16CodeUnits: dump, count: dump.count)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment