UInt16Extension.swift 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. //
  2. // UInt16Extension.swift
  3. // CryptoSwift
  4. //
  5. // Created by Marcin Krzyzanowski on 02/09/14.
  6. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
  7. //
  8. import Foundation
  9. /** Shift bits */
  10. extension UInt16 {
  11. /** Shift bits to the right. All bits are shifted (including sign bit) */
  12. mutating func shiftRight(count: UInt16) -> UInt16 {
  13. if (self == 0) {
  14. return self;
  15. }
  16. let bitsCount = UInt16(sizeofValue(self) * 8)
  17. if (count >= bitsCount) {
  18. return 0
  19. }
  20. let maxBitsForValue = UInt16(floor(log2(Double(self) + 1)))
  21. let shiftCount = Swift.min(count, maxBitsForValue - 1)
  22. var shiftedValue:UInt16 = 0;
  23. for bitIdx in 0..<bitsCount {
  24. let byte = 1 << bitIdx
  25. if ((self & byte) == byte) {
  26. shiftedValue = shiftedValue | (byte >> shiftCount)
  27. }
  28. }
  29. self = shiftedValue
  30. return self
  31. }
  32. }
  33. /** shift right and assign with bits truncation */
  34. func &>> (lhs: UInt16, rhs: UInt16) -> UInt16 {
  35. var l = lhs;
  36. l.shiftRight(rhs)
  37. return l
  38. }