Skip to content

Instantly share code, notes, and snippets.

@mstultz
Created May 17, 2019 16:51
Show Gist options
  • Save mstultz/87c9e855823614090fd682908e4649de to your computer and use it in GitHub Desktop.
Save mstultz/87c9e855823614090fd682908e4649de to your computer and use it in GitHub Desktop.
import UIKit
public enum Bit: Int {
case zero
case one
}
extension Bit {
func inverted() -> Bit {
return self == .zero ? .one : .zero
}
}
/** build bit pattern from array of bits */
@_specialize(exported: true, where T == UInt8)
func integerFrom<T: FixedWidthInteger>(_ bits: Array<Bit>) -> T {
var bitPattern: T = 0
for idx in bits.indices {
if bits[idx] == Bit.one {
let bit = T(UInt64(1) << UInt64(idx))
bitPattern = bitPattern | bit
}
}
return bitPattern
}
extension UInt8 {
init(bits: [Bit]) {
self.init(integerFrom(bits) as UInt8)
}
}
let expectedOutput: UInt8 = 0x47
let input: [Bit] = [
.zero,
.one,
.zero,
.zero,
.zero,
.one,
.one,
.one
]
let output = UInt8(bits: input)
print(expectedOutput) // 71
print(output) // 226
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment