Created
July 20, 2023 13:50
-
-
Save MLKrisJohnson/cf51a890c9f0e7163494c646c37d4905 to your computer and use it in GitHub Desktop.
Swift hexdump function
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 Cocoa | |
func printHexdump(data: Data) { | |
print("\n 0 1 2 3 4 5 6 7 8 9 a b c d e f") | |
print("-----------------------------------------------------------------------------") | |
var i = 0 | |
var bytes: [UInt8] = [] | |
while i < data.count { | |
if i % 16 == 0 { | |
// Write ASCII at end of previous line | |
if !bytes.isEmpty { | |
print(" \(String(bytes: bytes, encoding: .ascii)!)") | |
bytes = [] | |
} | |
// Write offset for this line | |
print(String(format: "%08x ", i), terminator: "") | |
} | |
else if i % 8 == 0 { | |
// Extra space between first eight bytes and last eight bytes | |
print(" ", terminator: "") | |
} | |
let byte = data[i] | |
print(String(format: " %02x", byte), terminator: "") | |
if byte >= 0x20 && byte <= 0x7e { | |
bytes.append(byte) | |
} else { | |
bytes.append(0x2e) // '.' | |
} | |
i += 1 | |
} | |
// Handle any remaining whitespace to fill 16-byte line. | |
while i % 16 != 0 { | |
if i % 8 == 0 { | |
// Extra space between first eight bytes and last eight bytes | |
print(" ", terminator: "") | |
} | |
print(" ..", terminator: "") | |
bytes.append(0x20) // ' ' | |
i += 1 | |
} | |
if !bytes.isEmpty { | |
print(" \(String(bytes: bytes, encoding: .ascii)!)") | |
} | |
print("\n") | |
} | |
let data = "One ring to rule them all, one ring to find them, one ring to bring them close and in the darkness bind them!".data(using: .utf8)! | |
printHexdump(data: data) | |
/* Example output | |
0 1 2 3 4 5 6 7 8 9 a b c d e f | |
----------------------------------------------------------------------------- | |
00000000 4f 6e 65 20 72 69 6e 67 20 74 6f 20 72 75 6c 65 One ring to rule | |
00000010 20 74 68 65 6d 20 61 6c 6c 2c 20 6f 6e 65 20 72 them all, one r | |
00000020 69 6e 67 20 74 6f 20 66 69 6e 64 20 74 68 65 6d ing to find them | |
00000030 2c 20 6f 6e 65 20 72 69 6e 67 20 74 6f 20 62 72 , one ring to br | |
00000040 69 6e 67 20 74 68 65 6d 20 63 6c 6f 73 65 20 61 ing them close a | |
00000050 6e 64 20 69 6e 20 74 68 65 20 64 61 72 6b 6e 65 nd in the darkne | |
00000060 73 73 20 62 69 6e 64 20 74 68 65 6d 21 .. .. .. ss bind them! | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment