Swiftpack.co -  nst/BinUtils as Swift Package
Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
Swift functions to ease working with binary formats
.package(url: "https://github.com/nst/BinUtils.git", from: "SWIFT_2_LAST_VERSION")


Swift functions to ease working with binary formats


Either copy BinUtils.swift into your project, or use Swift Package Manager by adding the following dependency to your Package.swift:

dependencies: [
    .Package(url: "https://github.com/nst/BinUtils.git", majorVersion: 0, minor: 1),


let data = "Hello".dataUsingEncoding(.utf8)!
assert(hexlify(data) == "48656C6C6F")


let s = String(data: unhexlify("48656C6C6F")!, encoding: .utf8)
assert(s == "Hello")

pack(fmt, [v1, v2, ...])

let d = pack("<h2I3sf", [1, 2, 3, "asd", 0.5])
assert(d == unhexlify("0100 02000000 03000000 617364 0000003f"))

unpack(fmt, string)

let a = unpack(">hBsf", unhexlify("0500 01 41 3fc00000")!)
assert(a[0] as? Int == 1280)
assert(a[1] as? Int == 1)
assert(a[2] as? String == "A")
assert(a[3] as? Double == 1.5)
let f = FileHandle(forReadingAtPath: "/bin/ls")!
let b = unpack("<2H", f.readDataOfLength(4))
assert(b[0] as? Int == 64207)
assert(b[1] as? Int == 65261)


pack() and unpack() should behave as Python's struct module https://docs.python.org/2/library/struct.html BUT:

  • native size and alignment @ is not supported
  • as a consequence, the byte order specifier character is mandatory and must be among =<>!
  • native byte order = assumes a little-endian system (eg. Intel x86)
  • Pascal strings p and native pointers P are not supported

Byte Order Format

Character Byte Order
= little-endian
< little-endian
> big-endian
! network (big-endian)

Format Characters

Format C Type Swift Type Size
x pad byte - 1
c char String of length 1 1
b signed char Int8 1
B unsigned char UInt8 1
? _Bool Bool 1
h short Int16 2
H unsigned short UInt16 2
i int Int32 4
I unsigned int UInt32 4
l long Int32 4
L unsigned long UInt32 4
q long long Int64 8
Q unsigned long long Int64 8
f float Float32 4
d double Float64 8
s char[] String


Stars: 60
Last commit: 2 years ago

Ad: Job Offers

iOS Software Engineer @ Perry Street Software
Perry Street Software is Jack’d and SCRUFF. We are two of the world’s largest gay, bi, trans and queer social dating apps on iOS and Android. Our brands reach more than 20 million members worldwide so members can connect, meet and express themselves on a platform that prioritizes privacy and security. We invest heavily into SwiftUI and using Swift Packages to modularize the codebase.

Submit a free job ad (while I'm testing this). The analytics numbers for this website are here.

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics