UInt8Extension.swift 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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. #if os(Linux)
  9. import Glibc
  10. #else
  11. import Darwin
  12. #endif
  13. public protocol _UInt8Type { }
  14. extension UInt8: _UInt8Type {}
  15. extension _UInt8Type {
  16. static func Zero() -> Self {
  17. return 0 as! Self
  18. }
  19. }
  20. /** casting */
  21. extension UInt8 {
  22. /** cast because UInt8(<UInt32>) because std initializer crash if value is > byte */
  23. static func withValue(v:UInt64) -> UInt8 {
  24. let tmp = v & 0xFF
  25. return UInt8(tmp)
  26. }
  27. static func withValue(v:UInt32) -> UInt8 {
  28. let tmp = v & 0xFF
  29. return UInt8(tmp)
  30. }
  31. static func withValue(v:UInt16) -> UInt8 {
  32. let tmp = v & 0xFF
  33. return UInt8(tmp)
  34. }
  35. }
  36. /** Bits */
  37. extension UInt8 {
  38. init(bits: [Bit]) {
  39. self.init(integerFromBitsArray(bits) as UInt8)
  40. }
  41. /** array of bits */
  42. func bits() -> [Bit] {
  43. let totalBitsCount = sizeofValue(self) * 8
  44. var bitsArray = [Bit](count: totalBitsCount, repeatedValue: Bit.Zero)
  45. for j in 0..<totalBitsCount {
  46. let bitVal:UInt8 = 1 << UInt8(totalBitsCount - 1 - j)
  47. let check = self & bitVal
  48. if (check != 0) {
  49. bitsArray[j] = Bit.One;
  50. }
  51. }
  52. return bitsArray
  53. }
  54. func bits() -> String {
  55. var s = String()
  56. let arr:[Bit] = self.bits()
  57. for (idx,b) in arr.enumerate() {
  58. s += (b == Bit.One ? "1" : "0")
  59. if ((idx + 1) % 8 == 0) { s += " " }
  60. }
  61. return s
  62. }
  63. }
  64. /** Shift bits */
  65. extension UInt8 {
  66. /** Shift bits to the right. All bits are shifted (including sign bit) */
  67. mutating func shiftRight(count: UInt8) -> UInt8 {
  68. if (self == 0) {
  69. return self;
  70. }
  71. let bitsCount = UInt8(sizeof(UInt8) * 8)
  72. if (count >= bitsCount) {
  73. return 0
  74. }
  75. let maxBitsForValue = UInt8(floor(log2(Double(self) + 1)))
  76. let shiftCount = Swift.min(count, maxBitsForValue - 1)
  77. var shiftedValue:UInt8 = 0;
  78. for bitIdx in 0..<bitsCount {
  79. let byte = 1 << bitIdx
  80. if ((self & byte) == byte) {
  81. shiftedValue = shiftedValue | (byte >> shiftCount)
  82. }
  83. }
  84. self = shiftedValue
  85. return self
  86. }
  87. }
  88. /** shift right and assign with bits truncation */
  89. func &>> (lhs: UInt8, rhs: UInt8) -> UInt8 {
  90. var l = lhs;
  91. l.shiftRight(rhs)
  92. return l
  93. }