Biginteger Equivalent in Swift

How to store Big Integer in Swift 4 Codable?

Use built-in Decimal which derives from NSDecimalNumber. It adopts Codable

Big Integer Swift 4.0

You can define a custom mod operator between two decimals such as follow. I haven't the time to test for all scenarios. So I'm selecting the simplest case: modulo between 2 positive numbers. You can expand it to suit your situation:

func % (lhs: Decimal, rhs: Decimal) -> Decimal {
precondition(lhs > 0 && rhs > 0)

if lhs < rhs {
return lhs
} else if lhs == rhs {
return 0
}

var quotient = lhs / rhs
var rounded = Decimal()
NSDecimalRound(&rounded, "ient, 0, .down)

return lhs - (rounded * rhs)
}

let a = Decimal(string: "083123456787654325500479087654")!
print(a % 55)

The result is 49.

Swift BigInt to [UInt8]

BigUInt has a

/// Return a `Data` value that contains the base-256 representation of this integer,
/// in network (big-endian) byte order.
public func serialize() -> Data

method (see Data Conversion.swift), so what you can do is

let bi: BigInt = ...
let bytes = Array(BigUInt(bi).serialize())

How do I convert a 50 digit string into the appropriate integer type in Swift?

The maximimum size of an Int64 is 9,223,372,036,854,775,807 when it is signed. So you cannot convert it just like that.

You need something like the BigInt class found in other languages. Check this other question where they answer with alternatives about BigInt in Swift:

  • BigInteger equivalent in Swift?

In summary, there are third-party libraries out there for arbitrary long integers. The only alternative from Apple is NSDecimalNumber but its limit is 38 digits, whereas your number has 50.

How to parse Int with a value more than 2147483647 from JSON in Swift

Int can be a 32-bit or 64-bit integer, depending on the platform.
As already said in the comments, you need Int64 or UInt64 to store
a value > 2147483647 on all platforms.

You cannot cast from AnyObject to Int64 directly, therefore
the conversion is via NSNumber:

guard let userId = (dict["id"] as? NSNumber)?.longLongValue  else { return }

For Swift 3, replace longLongValue by int64Value.



Related Topics



Leave a reply



Submit