UInt8+Extension.swift 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. //
  2. // CryptoSwift
  3. //
  4. // Copyright (C) 2014-2017 Marcin Krzyżanowski <marcin@krzyzanowskim.com>
  5. // This software is provided 'as-is', without any express or implied warranty.
  6. //
  7. // In no event will the authors be held liable for any damages arising from the use of this software.
  8. //
  9. // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
  10. //
  11. // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
  12. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  13. // - This notice may not be removed or altered from any source or binary distribution.
  14. //
  15. #if os(Linux) || os(Android) || os(FreeBSD)
  16. import Glibc
  17. #else
  18. import Darwin
  19. #endif
  20. public protocol _UInt8Type {}
  21. extension UInt8: _UInt8Type {}
  22. /** casting */
  23. extension UInt8 {
  24. /** cast because UInt8(<UInt32>) because std initializer crash if value is > byte */
  25. static func with(value: UInt64) -> UInt8 {
  26. let tmp = value & 0xff
  27. return UInt8(tmp)
  28. }
  29. static func with(value: UInt32) -> UInt8 {
  30. let tmp = value & 0xff
  31. return UInt8(tmp)
  32. }
  33. static func with(value: UInt16) -> UInt8 {
  34. let tmp = value & 0xff
  35. return UInt8(tmp)
  36. }
  37. }
  38. /** Bits */
  39. extension UInt8 {
  40. init(bits: [Bit]) {
  41. self.init(integerFrom(bits) as UInt8)
  42. }
  43. /** array of bits */
  44. public func bits() -> [Bit] {
  45. let totalBitsCount = MemoryLayout<UInt8>.size * 8
  46. var bitsArray = [Bit](repeating: Bit.zero, count: totalBitsCount)
  47. for j in 0..<totalBitsCount {
  48. let bitVal: UInt8 = 1 << UInt8(totalBitsCount - 1 - j)
  49. let check = self & bitVal
  50. if check != 0 {
  51. bitsArray[j] = Bit.one
  52. }
  53. }
  54. return bitsArray
  55. }
  56. public func bits() -> String {
  57. var s = String()
  58. let arr: [Bit] = bits()
  59. for idx in arr.indices {
  60. s += (arr[idx] == Bit.one ? "1" : "0")
  61. if idx.advanced(by: 1) % 8 == 0 { s += " " }
  62. }
  63. return s
  64. }
  65. }