UInt8+Extension.swift 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. //
  2. // CryptoSwift
  3. //
  4. // Copyright (C) 2014-2025 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 canImport(Darwin)
  16. import Darwin
  17. #elseif canImport(Android)
  18. import Android
  19. #elseif canImport(Glibc)
  20. import Glibc
  21. #elseif canImport(Musl)
  22. import Musl
  23. #elseif canImport(ucrt)
  24. import ucrt
  25. #endif
  26. public protocol _UInt8Type {}
  27. extension UInt8: _UInt8Type {}
  28. /** casting */
  29. extension UInt8 {
  30. /** cast because UInt8(<UInt32>) because std initializer crash if value is > byte */
  31. static func with(value: UInt64) -> UInt8 {
  32. let tmp = value & 0xff
  33. return UInt8(tmp)
  34. }
  35. static func with(value: UInt32) -> UInt8 {
  36. let tmp = value & 0xff
  37. return UInt8(tmp)
  38. }
  39. static func with(value: UInt16) -> UInt8 {
  40. let tmp = value & 0xff
  41. return UInt8(tmp)
  42. }
  43. }
  44. /** Bits */
  45. extension UInt8 {
  46. /** array of bits */
  47. public func bits() -> [Bit] {
  48. let totalBitsCount = MemoryLayout<UInt8>.size * 8
  49. var bitsArray = [Bit](repeating: Bit.zero, count: totalBitsCount)
  50. for j in 0..<totalBitsCount {
  51. let bitVal: UInt8 = 1 << UInt8(totalBitsCount - 1 - j)
  52. let check = self & bitVal
  53. if check != 0 {
  54. bitsArray[j] = Bit.one
  55. }
  56. }
  57. return bitsArray
  58. }
  59. public func bits() -> String {
  60. var s = String()
  61. let arr: [Bit] = self.bits()
  62. for idx in arr.indices {
  63. s += (arr[idx] == Bit.one ? "1" : "0")
  64. if idx.advanced(by: 1) % 8 == 0 { s += " " }
  65. }
  66. return s
  67. }
  68. }