Skip to content

Instantly share code, notes, and snippets.

@jepers
Last active April 14, 2019 11:15
Show Gist options
  • Save jepers/3a347775474f25077874268b1ebdd4ce to your computer and use it in GitHub Desktop.
Save jepers/3a347775474f25077874268b1ebdd4ce to your computer and use it in GitHub Desktop.
Like hexdump -C but in Swift 4.1
import Foundation
/// Writes a canonical hex+ASCII representation of `bytes` into `output`.
func hexdump<Target>(_ bytes: UnsafeRawBufferPointer, to output: inout Target)
where Target: TextOutputStream
{
guard bytes.count > 0 else { return }
var asciiString = ""
func startRow(offset: Int) {
print(String(format: "%08x", offset), terminator: " ", to: &output)
asciiString = ""
}
for byteIndex in bytes.indices {
if byteIndex & 15 == 0 { startRow(offset: byteIndex) }
let byteValue = bytes[byteIndex]
print(String(format: "%02x", byteValue), terminator: " ", to: &output)
if byteIndex & 7 == 7 { print(terminator: " ", to: &output) }
let asciiChar = (0x20 ... 0x7e).contains(byteValue) ? byteValue : 0x2e
asciiString.append(String(UnicodeScalar(asciiChar)))
if byteIndex & 15 == 15 { print("|" + asciiString + "|", to: &output) }
}
let emptyColumns = 15 - ((bytes.count - 1) & 15)
if emptyColumns > 0 {
let spaces = String(repeating: " ", count: (emptyColumns * 28) / 9)
print(spaces, "|" + asciiString + "|", to: &output)
}
startRow(offset: bytes.count)
print(terminator: "\n", to: &output)
}
/// Writes a canonical hex+ASCII representation of `bytes` to standard output.
func hexdump(_ bytes: UnsafeRawBufferPointer) {
struct StdOut : TextOutputStream {
mutating func write(_ string: String) { print(string, terminator: "") }
}
var hexdumpStdOut = StdOut()
hexdump(bytes, to: &hexdumpStdOut)
}
"👋Hello world!🌎".utf8.map({ $0 }).withUnsafeBytes(hexdump)
var log = "\nAll the bytes:\n"
(0 ... 255).map { UInt8($0) }.withUnsafeBytes { hexdump($0, to: &log) }
log += "\nSome random UInt32 values:\n"
(0 ..< 123).map { _ in arc4random() }.withUnsafeBytes { hexdump($0, to: &log) }
print(log)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment