UInt8+Extension.swift 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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) || os(Android) || os(FreeBSD)
  9. import Glibc
  10. #else
  11. import Darwin
  12. #endif
  13. public protocol _UInt8Type {}
  14. extension UInt8: _UInt8Type {}
  15. /** casting */
  16. extension UInt8 {
  17. /** cast because UInt8(<UInt32>) because std initializer crash if value is > byte */
  18. static func with(value: UInt64) -> UInt8 {
  19. let tmp = value & 0xFF
  20. return UInt8(tmp)
  21. }
  22. static func with(value: UInt32) -> UInt8 {
  23. let tmp = value & 0xFF
  24. return UInt8(tmp)
  25. }
  26. static func with(value: UInt16) -> UInt8 {
  27. let tmp = value & 0xFF
  28. return UInt8(tmp)
  29. }
  30. }
  31. /** Bits */
  32. extension UInt8 {
  33. init(bits: [Bit]) {
  34. self.init(integerFrom(bits) as UInt8)
  35. }
  36. /** array of bits */
  37. public func bits() -> [Bit] {
  38. let totalBitsCount = MemoryLayout<UInt8>.size * 8
  39. var bitsArray = [Bit](repeating: Bit.zero, count: totalBitsCount)
  40. for j in 0 ..< totalBitsCount {
  41. let bitVal: UInt8 = 1 << UInt8(totalBitsCount - 1 - j)
  42. let check = self & bitVal
  43. if (check != 0) {
  44. bitsArray[j] = Bit.one
  45. }
  46. }
  47. return bitsArray
  48. }
  49. public func bits() -> String {
  50. var s = String()
  51. let arr: [Bit] = self.bits()
  52. for idx in arr.indices {
  53. s += (arr[idx] == Bit.one ? "1" : "0")
  54. if (idx.advanced(by: 1) % 8 == 0) { s += " " }
  55. }
  56. return s
  57. }
  58. }