UInt8Extension.swift 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. //
  2. // ByteExtension.swift
  3. // CryptoSwift
  4. //
  5. // Created by Marcin Krzyzanowski on 07/08/14.
  6. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
  7. //
  8. import Foundation
  9. /** casting */
  10. extension UInt8 {
  11. /** cast because UInt8(<UInt32>) because std initializer crash if value is > byte */
  12. static func withValue(v:UInt64) -> UInt8 {
  13. let tmp = v & 0xFF
  14. return UInt8(tmp)
  15. }
  16. static func withValue(v:UInt32) -> UInt8 {
  17. let tmp = v & 0xFF
  18. return UInt8(tmp)
  19. }
  20. static func withValue(v:UInt16) -> UInt8 {
  21. let tmp = v & 0xFF
  22. return UInt8(tmp)
  23. }
  24. }
  25. /** Bits */
  26. extension UInt8 {
  27. init(bits: [Bit]) {
  28. self.init(integerFromBitsArray(bits) as UInt8)
  29. }
  30. /** array of bits */
  31. func bits() -> [Bit] {
  32. let totalBitsCount = sizeofValue(self) * 8
  33. var bitsArray = [Bit](count: totalBitsCount, repeatedValue: Bit.Zero)
  34. for j in 0..<totalBitsCount {
  35. let bitVal:UInt8 = 1 << UInt8(totalBitsCount - 1 - j)
  36. let check = self & bitVal
  37. if (check != 0) {
  38. bitsArray[j] = Bit.One;
  39. }
  40. }
  41. return bitsArray
  42. }
  43. func bits() -> String {
  44. var s = String()
  45. let arr:[Bit] = self.bits()
  46. for (idx,b) in enumerate(arr) {
  47. s += (b == Bit.One ? "1" : "0")
  48. if ((idx + 1) % 8 == 0) { s += " " }
  49. }
  50. return s
  51. }
  52. }
  53. /** Shift bits */
  54. extension UInt8 {
  55. /** Shift bits to the right. All bits are shifted (including sign bit) */
  56. mutating func shiftRight(count: UInt8) -> UInt8 {
  57. if (self == 0) {
  58. return self;
  59. }
  60. var bitsCount = UInt8(sizeof(UInt8) * 8)
  61. if (count >= bitsCount) {
  62. return 0
  63. }
  64. var maxBitsForValue = UInt8(floor(log2(Double(self) + 1)))
  65. var shiftCount = Swift.min(count, maxBitsForValue - 1)
  66. var shiftedValue:UInt8 = 0;
  67. for bitIdx in 0..<bitsCount {
  68. var byte = 1 << bitIdx
  69. if ((self & byte) == byte) {
  70. shiftedValue = shiftedValue | (byte >> shiftCount)
  71. }
  72. }
  73. self = shiftedValue
  74. return self
  75. }
  76. }
  77. /** shift right and assign with bits truncation */
  78. func &>> (lhs: UInt8, rhs: UInt8) -> UInt8 {
  79. var l = lhs;
  80. l.shiftRight(rhs)
  81. return l
  82. }