Skip to content

Instantly share code, notes, and snippets.

@robnadin
Last active April 28, 2020 13:28
Show Gist options
  • Save robnadin/04d7d74c4273e8def73d2ed7fb0d0774 to your computer and use it in GitHub Desktop.
Save robnadin/04d7d74c4273e8def73d2ed7fb0d0774 to your computer and use it in GitHub Desktop.
extension FixedWidthInteger {
public init<C: Collection>(littleEndianBytes bytes: C) where C.Element == UInt8 {
let (quotient, remainder) = Self.bitWidth.quotientAndRemainder(dividingBy: 8)
precondition(bytes.count == (quotient + remainder.signum())
var iterator = bytes.makeIterator()
self.init(littleEndianBytes: &iterator)
}
public init<I: IteratorProtocol>(littleEndianBytes iterator: inout I) where I.Element == UInt8 {
self = stride(from: 0, to: Self.bitWidth, by: 8).reduce(into: 0) {
$0 |= Self(truncatingIfNeeded: iterator.next()!) &<< $1
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment