Last active
April 28, 2020 13:28
-
-
Save robnadin/04d7d74c4273e8def73d2ed7fb0d0774 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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