Is there a number type with bigger capacity than u_long/UInt64 in Swift?

后端 未结 4 479
鱼传尺愫
鱼传尺愫 2021-01-19 06:21

Is there a type with bigger capacity than u_long or UInt64 in Swift?

I have a function that takes very big integers to identify a credit card numbe

相关标签:
4条回答
  • 2021-01-19 06:36

    I'm working on a BigNumber library with which you can do some big number calculations. Actually the library is based on the GNU Multiple Precision (GMP) library (see: https://gmplib.org) and I wrote an Objective-C / Swift wrapper. Currently big integer mathematics, including a lot of operator overloading, is possible. A code example goes like:

    var err : NSError?
    var bi1 = BigInt(nr: 12468642135797531)
    var bi2 = BigInt(nr: "12345678901011121314151617181920", error: &err)
    var res = bi1 * bi2
    println("Multiply 2 BigInts: bi1 * bi2 = \(res.toString())")
    

    which results in:

    Multiply 2 BigInts: bi1 * bi2 = 153933852140173822960829726365674325601913839520
    

    You can find the library at: https://github.com/githotto/osxgmp

    I think its fairly easy to do some 'credit-card-number' math with even numbers having far more than 28-digits.

    0 讨论(0)
  • 2021-01-19 06:36

    Another approach would be to work with strings, and define the mathematical operators to operate on strings also:

    func +(lhs: String, rhs: Int8) -> String
    func +(lhs: String, rhs: Int16) -> String
    func +(lhs: String, rhs: Int32) -> String
    func +(lhs: String, rhs: Int64) -> String
    func +(lhs: String, rhs: String) -> String
    // ... other operators
    

    This has the advantage of theoretically allowing and unlimited number of digits, but has the disadvantage of the fact that the strings might not always represent numbers.

    0 讨论(0)
  • 2021-01-19 06:57

    You can implement your own UInt128 type. Or use NSDecimalNumber

    To implement UInt128

    struct UInt128 {
        var low : UInt64 = 0;
        var high : UInt64 = 0;
    }
    

    and you can implement operators

    infix func + (l: UInt128, r: UInt128) -> UInt128 {
        // do your work... care with overflow 
    }
    
    0 讨论(0)
  • 2021-01-19 07:00

    A credit card number is not a number in a meaningful mathematical sense. It is a sequence of digits and a CC should be treated as text, much like a phone number. One immediate issue of using a fixed-length integer value is that code cannot simultaneously detect leading and trailing zeros from "no more numbers present".

    Use a string or a specific (custom) type representing the CC number, probably using a string internally. The length of the number (in base-10) is then trivially the number of digits: which is the length of the underlying string.

    The CC number (represented by a bonafide string) can later be encoded into an appropriate binary representation, if (and when) required.

    0 讨论(0)
提交回复
热议问题