Reputation: 18591
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 number with 28 digits:
func myFunc(number : /*What to put here?*/) {
//body
}
what type is appropriate? should number be treated as a string?
Upvotes: 4
Views: 2034
Reputation: 32870
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.
Upvotes: 0
Reputation: 1241
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.
Upvotes: 2
Reputation: 61975
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.
Upvotes: 15
Reputation: 46608
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
}
Upvotes: 5