UInt8+Extension.swift 2.3 KB

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