Skip to content

Instantly share code, notes, and snippets.

@krzyzanowskim
Last active August 29, 2015 14:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krzyzanowskim/8dc3962e771c9eead59b to your computer and use it in GitHub Desktop.
Save krzyzanowskim/8dc3962e771c9eead59b to your computer and use it in GitHub Desktop.
Shift bits to the left - Generic version. This is the most advanced Generic function I ever wrote (req: extensions, protocol, funcs)
// Playground - noun: a place where people can play
import Foundation
/** Protocol and extensions for integerFromBitsArray. Bit hakish for me, but I can't do it in any other way */
protocol Initiable {
init(_ v: Int)
init(_ v: UInt)
}
extension Int:Initiable {}
extension UInt:Initiable {}
// helper to be able tomake shift operation on T
func <<<T:SignedIntegerType>(lhs: T, rhs: Int) -> Int {
let a = lhs as Int
let b = rhs
return a << b
}
func <<<T:UnsignedIntegerType>(lhs: T, rhs: Int) -> UInt {
let a = lhs as UInt
let b = rhs
return a << b
}
// Generic function itself
func shiftLeft<T: SignedIntegerType where T: Initiable>(value: T, count: Int) -> T {
if (value == 0) {
return 0;
}
var bitsCount = sizeofValue(value) * 8
var shiftCount = Int(Swift.min(count, bitsCount - 1))
var shiftedValue:T = 0;
for bitIdx in 0..<bitsCount {
var bit = T(1 << bitIdx)
if ((value & bit) == bit) {
shiftedValue = shiftedValue | T(bit << shiftCount)
}
}
return shiftedValue
}
// for any f*** other Integer type - this part is so non-Generic
func shiftLeft(value: UInt, count: Int) -> UInt {
return UInt(shiftLeft(UInt(value), count))
}
func shiftLeft(value: UInt8, count: Int) -> UInt8 {
return UInt8(shiftLeft(UInt(value), count))
}
func shiftLeft(value: UInt16, count: Int) -> UInt16 {
return UInt16(shiftLeft(UInt(value), count))
}
func shiftLeft(value: UInt32, count: Int) -> UInt32 {
return UInt32(shiftLeft(UInt(value), count))
}
func shiftLeft(value: UInt64, count: Int) -> UInt64 {
return UInt64(shiftLeft(UInt(value), count))
}
func shiftLeft(value: Int8, count: Int) -> Int8 {
return Int8(shiftLeft(Int(value), count))
}
func shiftLeft(value: Int16, count: Int) -> Int16 {
return Int16(shiftLeft(Int(value), count))
}
func shiftLeft(value: Int32, count: Int) -> Int32 {
return Int32(shiftLeft(Int(value), count))
}
func shiftLeft(value: Int64, count: Int) -> Int64 {
return Int64(shiftLeft(Int(value), count))
}
// testing
shiftLeft(1, 2) as UInt
shiftLeft(1, 2) as UInt8
shiftLeft(1, 2) as UInt16
shiftLeft(1, 2) as UInt32
shiftLeft(1, 2) as UInt64
shiftLeft(1, 2) as Int
shiftLeft(1, 2) as Int8
shiftLeft(1, 2) as Int16
shiftLeft(1, 2) as Int32
shiftLeft(1, 2) as Int64
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment