I recently ran across the need for a large integer in Swift – something that needs more than the 64 bits provided by Int64. This is not the first time. I have played around with Swift Decimal in the past (NSDecimal, NSDecimalNumber) only to find they come up short in precisely representing a rational number. Python, for example, makes it trivial to find the Nth decimal place of any rational number by storing the repeating decimal pattern under the hood and making that info available to you.
This poor substitute of mine only supports the binary OR and POPULATION operations and has no string representation. But it worked for what I needed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
//: Playground - noun: a place where people can play import Cocoa struct Bin { var value: [UInt64] = Array<UInt64>(repeating: 0, count: 10) // LSD at [0] init() { } init(_ string: String) { var index = 0 var finish = string.endIndex repeat { let start = string.index(finish, offsetBy: -64, limitedBy: string.startIndex) ?? string.startIndex value[index] = UInt64(string[start..<finish], radix: 2)! finish = start index += 1 } while finish != string.startIndex } static func | (lhs: Bin, rhs: Bin) -> Bin { var c = Bin() for (n, (a, b)) in zip(lhs.value, rhs.value).enumerated() { c.value[n] = a | b } return c } func population() -> Int { var pop = 0 for v in value { var a = v while a > 0 { pop += Int(a % UInt64(2) & 1) a /= 2 } } return pop } } let x = Bin("10000000000000000000000000000000000000000000000000000000000000000") let a = Bin("10101010101010101010101010101010101010101010101010101010101010101010101010") a.population() let b = Bin("01010101010101010101010101010101010101010101010101010101010101010101010101") b.population() let c = a | b c.population() |