### Quick Setup and Serialization Sample Source: https://github.com/ionspin/kotlin-multiplatform-bignum/blob/main/bignum-serialization-kotlinx/README.md Demonstrates basic setup for KotlinX Serialization with BigInteger and BigDecimal, including encoding and decoding a data class. ```kotlin val json = Json { serializersModule = arrayBasedSerializerModule // or humanReadableSerializerModule } @Serializable data class SomeDataHolder(@Contextual val bigInteger: BigInteger, @Contextual val bigDecimal: BigDecimal) @Test fun serializeAndDeserialize() { val bigInt = BigInteger.parseString("12345678901234567890") val bigDecimal = BigDecimal.parseString("1.234E-200") val someData = SomeDataHolder(bigInt, bigDecimal) val serialized = json.encodeToString(someData) println(serialized) val deserialized = json.decodeFromString(serialized) assertEquals(someData, deserialized) } ``` -------------------------------- ### Initialize BigDecimal operands Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigDecimal-Architecture-and-Implementation Example of creating BigDecimal instances from strings. ```kotlin val a = "123".toBigDecimal() // significand = 123, precision = 3, exponent = 2 so 1.23E+2 val b = "456".toBigDecimal() // significand = 456, precision = 3, exponent = 2 so 4.56E+2 ``` -------------------------------- ### Handle infinite division Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigDecimal-Architecture-and-Implementation Example of a division operation that results in an infinite repeating decimal. ```kotlin val a = 1.toBigDecimal() val b = a / 3 ``` -------------------------------- ### Perform division with remainder Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigDecimal-Architecture-and-Implementation Example of a division operation that results in a remainder. ```kotlin val a = Float.MIN_VALUE.toBigDecimal() // Creates a big decimal with significand 14 val divided = a / 10 ``` -------------------------------- ### Convert String to BigDecimal using extension function Source: https://github.com/ionspin/kotlin-multiplatform-bignum/blob/main/README.md Use the `toBigInteger` extension function on a String to convert it to a BigDecimal. Note: This example seems to have a typo and should likely be `toBigDecimal`. ```kotlin val bigDecimal = "12345678.123".toBigInteger ``` -------------------------------- ### BigInteger Precise Inversion Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigInteger-Usage-Overview Perform a precise bitwise inversion on a BigInteger using `invPrecise()`. Unlike two's complement inversion, this flips each bit individually. For example, binary '1100' becomes '0011'. ```kotlin val operand = BigInteger.parseString("11110000", 2) val invResult = operand.invPrecise() println("Inv result: ${invResult.toString(2)}") ``` -------------------------------- ### Create BigDecimal Instances Source: https://context7.com/ionspin/kotlin-multiplatform-bignum/llms.txt Shows how to instantiate BigDecimal from strings, primitives, and using extension functions. ```kotlin import com.ionspin.kotlin.bignum.decimal.BigDecimal import com.ionspin.kotlin.bignum.decimal.toBigDecimal // Parse from string - scientific notation val scientific = BigDecimal.parseString("1.23E-6") println("Scientific: $scientific") // Output: 1.23E-6 // Parse from string - expanded notation val expanded = BigDecimal.parseString("0.00000123") println("Expanded: $expanded") // Output: 1.23E-6 // From primitive types val fromLong = BigDecimal.fromLong(7111) println("From Long 7111: $fromLong") // Output: 7.111E+3 val fromDouble = BigDecimal.fromDouble(123.456) println("From Double: $fromDouble") // Output: 1.23456E+2 // With explicit exponent val withExponent = BigDecimal.fromLongWithExponent(1, -5L) println("With exponent: $withExponent") println("Expanded form: ${withExponent.toStringExpanded()}") // Output: 1.0E-5 // Output: 0.00001 // Using extension functions val extDecimal = "12345.6789".toBigDecimal() val extFloat = 123.456f.toBigDecimal() val extInt = 1000.toBigDecimal() println("From string extension: $extDecimal") // Output: 1.23456789E+4 ``` -------------------------------- ### Snapshot build configuration Source: https://github.com/ionspin/kotlin-multiplatform-bignum/blob/main/README.md Repository and dependency configuration for using snapshot builds. ```kotlin repositories { maven { url = uri("https://oss.sonatype.org/content/repositories/snapshots") } } implementation("com.ionspin.kotlin:bignum:0.3.11-SNAPSHOT") ``` -------------------------------- ### Creating BigInteger instances Source: https://github.com/ionspin/kotlin-multiplatform-bignum/blob/main/README.md Various methods to instantiate BigInteger from strings, primitives, or extension functions. ```kotlin BigInteger.parse("-1122334455667788990011223344556677889900", 10) ``` ```kotlin val bigIntegerExtension = 234L.toBigInteger() val bigIntegerCompanion = BigInteger.fromLong(234L) ``` ```kotlin "12345678".toBigInteger() ``` -------------------------------- ### Perform Advanced BigInteger Operations Source: https://context7.com/ionspin/kotlin-multiplatform-bignum/llms.txt Demonstrates GCD, modular inverse, square root, factorial, and byte array conversions for BigInteger. ```kotlin import com.ionspin.kotlin.bignum.integer.BigInteger // Greatest Common Divisor val gcdA = BigInteger.fromInt(48) val gcdB = BigInteger.fromInt(18) val gcdResult = gcdA.gcd(gcdB) println("GCD of 48 and 18: $gcdResult") // Output: 6 // Modular Inverse val value = BigInteger.fromInt(3) val modulo = BigInteger.fromInt(11) val modInverse = value.modInverse(modulo) println("Modular inverse of 3 mod 11: $modInverse") // Output: 4 (because 3 * 4 = 12 = 1 mod 11) // Square Root val sqrtValue = BigInteger.fromInt(144) val sqrtResult = sqrtValue.sqrt() println("Square root of 144: $sqrtResult") // Output: 12 // Factorial val factorial = BigInteger.fromInt(10).factorial() println("10!: $factorial") // Output: 3628800 // Byte array conversion val bigInt = BigInteger.fromULong(ULong.MAX_VALUE) val byteArray = bigInt.toByteArray() val reconstructed = BigInteger.fromByteArray(byteArray, com.ionspin.kotlin.bignum.integer.Sign.POSITIVE) println("Reconstructed equals original: ${bigInt == reconstructed}") // Output: true // Two's complement conversion val negative = BigInteger.parseString("-AABBCC", 16) val twosComplement = negative.toTwosComplementByteArray() val fromTwos = BigInteger.fromTwosComplementByteArray(twosComplement) println("Two's complement round-trip: ${negative == fromTwos}") // Output: true ``` -------------------------------- ### Gradle dependency integration Source: https://github.com/ionspin/kotlin-multiplatform-bignum/blob/main/README.md Standard dependency declaration for the library. ```kotlin implementation("com.ionspin.kotlin:bignum:0.3.10") ``` -------------------------------- ### Perform Modular Arithmetic with ModularBigInteger Source: https://context7.com/ionspin/kotlin-multiplatform-bignum/llms.txt Create modular integers for a specific modulus and perform arithmetic operations, modular inverse, and exponentiation. ```kotlin import com.ionspin.kotlin.bignum.modular.ModularBigInteger import com.ionspin.kotlin.bignum.integer.BigInteger import com.ionspin.kotlin.bignum.integer.toBigInteger // Create a creator for a specific modulus val creator = ModularBigInteger.creatorForModulo(100) // Create modular integers val modA = creator.fromLong(150) // 150 mod 100 = 50 val modB = creator.fromLong(75) // 75 mod 100 = 75 println("150 mod 100 = ${modA.toStringWithModulo()}") // Output: 50 mod 100 // Arithmetic operations (automatically reduced by modulus) val sum = modA + modB // (50 + 75) mod 100 = 25 val diff = modA - modB // (50 - 75) mod 100 = 75 (wraps around) val product = modA * modB // (50 * 75) mod 100 = 50 println("Sum: ${sum.toStringWithModulo()}") // 25 mod 100 println("Difference: ${diff.toStringWithModulo()}") // 75 mod 100 println("Product: ${product.toStringWithModulo()}") // 50 mod 100 // Converting BigInteger to ModularBigInteger val bigInt = 100_002.toBigInteger() val modular = bigInt.toModularBigInteger(500.toBigInteger()) println("100002 mod 500 = ${modular.toStringWithModulo()}") // Output: 2 mod 500 // Modular inverse val primeCreator = ModularBigInteger.creatorForModulo(17) val value = primeCreator.fromLong(3) val inverse = value.inverse() println("Inverse of 3 mod 17 = ${inverse.toStringWithModulo()}") // Output: 6 mod 17 (because 3 * 6 = 18 = 1 mod 17) // Modular exponentiation val base = primeCreator.fromLong(2) val powered = base.pow(BigInteger.fromInt(10)) println("2^10 mod 17 = ${powered.toStringWithModulo()}") // Output: 4 mod 17 ``` -------------------------------- ### KotlinX Serialization for BigInteger and BigDecimal Source: https://context7.com/ionspin/kotlin-multiplatform-bignum/llms.txt Demonstrates how to serialize and deserialize BigInteger and BigDecimal using KotlinX Serialization with both human-readable and array-based formats. Ensure the appropriate serializer modules are imported. ```kotlin import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import kotlinx.serialization.Contextual import com.ionspin.kotlin.bignum.integer.BigInteger import com.ionspin.kotlin.bignum.decimal.BigDecimal // Import serializer modules from bignum-serialization-kotlinx // Define data class with BigNum types @Serializable data class FinancialData( @Contextual val amount: BigDecimal, @Contextual val transactionId: BigInteger ) // Human-readable serialization val jsonHumanReadable = Json { serializersModule = humanReadableSerializerModule } val data = FinancialData( amount = BigDecimal.parseString("1234567890.123456789"), transactionId = BigInteger.parseString("9999999999999999999999") ) val serialized = jsonHumanReadable.encodeToString(FinancialData.serializer(), data) println(serialized) // Output: {"amount":"1234567890.123456789","transactionId":"9999999999999999999999"} val deserialized = jsonHumanReadable.decodeFromString(FinancialData.serializer(), serialized) println("Deserialized amount: ${deserialized.amount.toStringExpanded()}") // Array-based serialization (faster, but less readable) val jsonArrayBased = Json { serializersModule = arrayBasedSerializerModule } val serializedArray = jsonArrayBased.encodeToString(FinancialData.serializer(), data) // Output: {"amount":{"significand":{"magnitude":[...],"sign":"POSITIVE"},"exponent":9},"transactionId":{"magnitude":[...],"sign":"POSITIVE"}} ``` -------------------------------- ### Perform Division with DecimalMode Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigDecimal-Usage-Overview Demonstrates division operations with explicit precision and rounding mode settings. ```kotlin fun readmeDivisionTest() { assertFailsWith(ArithmeticException::class) { val a = 1.toBigDecimal() val b = 3.toBigDecimal() val result = a/b } assertTrue { val a = 1.toBigDecimal() val b = 3.toBigDecimal() val result = a.div(b, DecimalMode(20, RoundingMode.ROUND_HALF_AWAY_FROM_ZERO)) result.toString() == "3.3333333333333333333E-1" } } ``` -------------------------------- ### Create BigInteger Instances in Kotlin Source: https://context7.com/ionspin/kotlin-multiplatform-bignum/llms.txt Instantiate BigInteger objects from strings with specified bases, primitive types using companion functions, or by using extension functions for convenience. ```kotlin import com.ionspin.kotlin.bignum.integer.BigInteger import com.ionspin.kotlin.bignum.integer.toBigInteger // Parse from string with base val fromString = BigInteger.parseString("-1122334455667788990011223344556677889900", 10) val hexValue = BigInteger.parseString("FFFFFFFFFF000000000000", 16) val binaryValue = BigInteger.parseString("11110000", 2) // From primitive types using companion functions val fromLong = BigInteger.fromLong(Long.MAX_VALUE) val fromInt = BigInteger.fromInt(Int.MAX_VALUE) val fromULong = BigInteger.fromULong(ULong.MAX_VALUE) // Using extension functions val extensionLong = 234L.toBigInteger() val extensionString = "12345678".toBigInteger() val extensionHex = "FF".toBigInteger(16) println("fromString: $fromString") // Output: -1122334455667788990011223344556677889900 println("extensionLong: $extensionLong") // Output: 234 ``` -------------------------------- ### Perform Division with Specific DecimalMode Source: https://github.com/ionspin/kotlin-multiplatform-bignum/blob/main/README.md Shows how to perform division with a specified DecimalMode to control precision and rounding. The result is checked against an expected string representation. ```kotlin assertTrue { val a = 1.toBigDecimal() val b = 3.toBigDecimal() val result = a.div(b, DecimalMode(20, RoundingMode.ROUND_HALF_AWAY_FROM_ZERO)) result.toString() == "3.3333333333333333333E-1" } } ``` -------------------------------- ### Handle ArithmeticException in Division Source: https://github.com/ionspin/kotlin-multiplatform-bignum/blob/main/README.md Demonstrates how to catch an ArithmeticException that may occur during division when precision is not sufficient or rounding is not specified. ```kotlin fun readmeDivisionTest() { assertFailsWith(ArithmeticException::class) { val a = 1.toBigDecimal() val b = 3.toBigDecimal() val result = a/b } ``` -------------------------------- ### WASM BigDecimal conversion behavior Source: https://github.com/ionspin/kotlin-multiplatform-bignum/blob/main/README.md Demonstrates the IEEE-754 conversion behavior specific to the experimental WASM platform. ```kotlin val a = BigDecimal.fromFloat(0.000000000000123f) ``` -------------------------------- ### Prepare dividend for division Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigDecimal-Architecture-and-Implementation Formula used to increase the precision of the dividend before division. ```kotlin val power = (other.precision * 2 + 6) val thisPrepared = this.significand * BigInteger.TEN.pow(power) ``` -------------------------------- ### BigInteger Division (Quotient and Remainder) Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigInteger-Usage-Overview Compute both the quotient and remainder of a BigInteger division simultaneously using the `divrem` function. This is efficient when both values are required. ```kotlin val a = BigInteger.fromLong(Long.MAX_VALUE) val b = BigInteger.fromInt(Int.MAX_VALUE) val dividend = a + b val divisor = BigInteger.fromLong(Long.MAX_VALUE) val quotientAndRemainder = dividend divrem divisor println("Quotient: ${quotientAndRemainder.quotient} Remainder: ${quotientAndRemainder.remainder}") ``` -------------------------------- ### Create BigInteger from String Extension Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigInteger-Usage-Overview Use the `toBigInteger()` extension function on strings to easily convert string representations of numbers into BigInteger objects. This is a convenient shorthand for parsing. ```kotlin "12345678".toBigInteger() ``` -------------------------------- ### BigInteger and BigDecimal Conversion Extensions Source: https://context7.com/ionspin/kotlin-multiplatform-bignum/llms.txt Shows how to use extension functions to convert Kotlin primitive types (Int, Long, Double) and String representations into BigInteger and BigDecimal objects. This facilitates easy initialization of BigNum types. ```kotlin import com.ionspin.kotlin.bignum.integer.BigInteger import com.ionspin.kotlin.bignum.integer.toBigInteger import com.ionspin.kotlin.bignum.decimal.BigDecimal import com.ionspin.kotlin.bignum.decimal.toBigDecimal // Conversion extensions val intToBig = 12345.toBigInteger() val stringToBig = "DEADBEEF".toBigInteger(16) val doubleToBigDec = 3.14159.toBigDecimal() val stringToBigDec = "123.456E+10".toBigDecimal() ``` -------------------------------- ### Parse BigDecimal from Expanded Notation Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigDecimal-Usage-Overview Create a BigDecimal instance by parsing a string in expanded notation. ```kotlin val bigDecimal = BigDecimal.parseString("0.00000123") println("BigDecimal: $bigDecimal") ``` -------------------------------- ### Create and Use Modular Integers in Kotlin Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/ModularBigInteger-Usage-Overview Define a modulo and create modular BigIntegers using the creator. Use `toStringWithModulo()` to display the modular representation. ```kotlin val creator = ModularBigInteger.creatorForModulo(100) val modularBigInteger = creator.fromLong(150) println("ModularBigInteger: ${modularBigInteger.toStringWithModulo()}") ``` -------------------------------- ### Configure BigDecimal Precision and Rounding Source: https://context7.com/ionspin/kotlin-multiplatform-bignum/llms.txt Use DecimalMode to define precision and scale, or apply specific rounding modes directly to BigDecimal values. ```kotlin import com.ionspin.kotlin.bignum.decimal.BigDecimal import com.ionspin.kotlin.bignum.decimal.DecimalMode import com.ionspin.kotlin.bignum.decimal.RoundingMode // DecimalMode with precision and rounding val mode = DecimalMode( decimalPrecision = 10, roundingMode = RoundingMode.ROUND_HALF_AWAY_FROM_ZERO, scale = 2 // digits after decimal point ) // Rounding to specific digit position after decimal val value = BigDecimal.parseString("1234.5678") val rounded = value.roundToDigitPositionAfterDecimalPoint(2, RoundingMode.CEILING) println("Rounded to 2 decimal places (CEILING): ${rounded.toStringExpanded()}") // Output: 1234.57 // Rounding to specific digit position (total precision) val value2 = BigDecimal.parseString("1234.5678") val rounded2 = value2.roundToDigitPosition(3, RoundingMode.ROUND_HALF_TOWARDS_ZERO) println("Rounded to 3 significant digits: ${rounded2.toStringExpanded()}") // Output: 1230 // Floor and Ceiling val decimal = BigDecimal.parseString("3.7") println("Floor: ${decimal.floor().toStringExpanded()}") // 3 println("Ceiling: ${decimal.ceil().toStringExpanded()}") // 4 // Available RoundingModes: // FLOOR - Towards negative infinity // CEILING - Towards positive infinity // AWAY_FROM_ZERO - Away from zero // TOWARDS_ZERO - Towards zero // NONE - Infinite precision (throws on non-terminating) // ROUND_HALF_AWAY_FROM_ZERO - Standard rounding // ROUND_HALF_TOWARDS_ZERO - Round half towards zero // ROUND_HALF_CEILING - Round half towards positive infinity // ROUND_HALF_FLOOR - Round half towards negative infinity // ROUND_HALF_TO_EVEN - Banker's rounding // ROUND_HALF_TO_ODD - Round half to odd ``` -------------------------------- ### Create ModularBigInteger Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigInteger-Usage-Overview Convert a BigInteger to a ModularBigInteger with a specified modulo using `toModularBigInteger()`. This is the first step in performing modular arithmetic operations. ```kotlin val a = 100_002.toBigInteger() val modularA = a.toModularBigInteger(500.toBigInteger()) println("ModularBigInteger: ${modularA.toStringWithModulo()}") ``` -------------------------------- ### Create BigInteger from Long/Int/Byte/Short Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigInteger-Usage-Overview Utilize extension functions like `toBigInteger()` or companion functions like `BigInteger.fromLong()` to convert primitive numeric types to BigInteger. This is useful for initializing BigIntegers with known values. ```kotlin val bigIntegerExtension = 234L.toBigInteger() val bigIntegerCompanion = BigInteger.fromLong(234L) ``` -------------------------------- ### Gradle Dependency for Snapshot Builds Source: https://github.com/ionspin/kotlin-multiplatform-bignum/blob/main/bignum-serialization-kotlinx/README.md Configure your Gradle repositories to include snapshots and add the snapshot dependency for the bignum library. ```kotlin repositories { maven { url = uri("https://oss.sonatype.org/content/repositories/snapshots") } } implementation("com.ionspin.kotlin:bignum:0.3.3-SNAPSHOT") ``` -------------------------------- ### Perform BigDecimal Arithmetic Source: https://context7.com/ionspin/kotlin-multiplatform-bignum/llms.txt Covers basic arithmetic and division with DecimalMode for precision control. ```kotlin import com.ionspin.kotlin.bignum.decimal.BigDecimal import com.ionspin.kotlin.bignum.decimal.DecimalMode import com.ionspin.kotlin.bignum.decimal.RoundingMode val a = BigDecimal.parseString("123.456") val b = BigDecimal.parseString("78.9") // Basic arithmetic val sum = a + b val diff = a - b val product = a * b println("Sum: ${sum.toStringExpanded()}") // 202.356 println("Difference: ${diff.toStringExpanded()}") // 44.556 println("Product: ${product.toStringExpanded()}") // 9740.6784 // Division requires precision specification for non-terminating results val dividend = 1.toBigDecimal() val divisor = 3.toBigDecimal() // This would throw ArithmeticException without DecimalMode: // val result = dividend / divisor // Use DecimalMode to specify precision and rounding val decimalMode = DecimalMode(20, RoundingMode.ROUND_HALF_AWAY_FROM_ZERO) val divisionResult = dividend.divide(divisor, decimalMode) println("1/3 with 20 digits precision: $divisionResult") // Output: 3.3333333333333333333E-1 // Exponentiation val power = BigDecimal.parseString("2.5").pow(3) println("2.5^3: ${power.toStringExpanded()}") // Output: 15.625 ``` -------------------------------- ### Add Kotlin Multiplatform BigNum to Gradle Dependencies Source: https://context7.com/ionspin/kotlin-multiplatform-bignum/llms.txt Add the library to your Gradle build file to include its functionality. For serialization support, add the specific serialization artifact. ```kotlin // build.gradle.kts implementation("com.ionspin.kotlin:bignum:0.3.10") // For serialization support implementation("com.ionspin.kotlin:bignum-serialization-kotlinx:0.3.2") ``` -------------------------------- ### Parse BigDecimal from Scientific Notation Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigDecimal-Usage-Overview Create a BigDecimal instance by parsing a string in scientific notation. ```kotlin val bigDecimal = BigDecimal.parseString("1.23E-6)") println("BigDecimal: $bigDecimal") ``` -------------------------------- ### BigInteger Division (Quotient) Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigInteger-Usage-Overview Calculate the quotient of a BigInteger division using the `/` operator. This returns the whole number result of the division, discarding any remainder. ```kotlin val a = BigInteger.fromLong(Long.MAX_VALUE) val b = BigInteger.fromInt(Int.MAX_VALUE) val dividend = a + b val divisor = BigInteger.fromLong(Long.MAX_VALUE) val quotient = dividend / divisor println("Quotient: $quotient") ``` -------------------------------- ### Perform BigInteger Arithmetic Operations in Kotlin Source: https://context7.com/ionspin/kotlin-multiplatform-bignum/llms.txt Utilize standard arithmetic operators and methods for addition, subtraction, multiplication, division, and modulo operations on BigInteger values. The `divrem` function efficiently computes both quotient and remainder. ```kotlin import com.ionspin.kotlin.bignum.integer.BigInteger val a = BigInteger.fromLong(Long.MAX_VALUE) // 9223372036854775807 val b = BigInteger.fromInt(Int.MAX_VALUE) // 2147483647 // Addition val sum = a + b println("Sum: $sum") // Output: Sum: 9223372039002259454 // Subtraction val difference = a - b println("Difference: $difference") // Output: Difference: 9223372034707292160 // Multiplication val product = a * b println("Product: $product") // Output: Product: 19807040619342712359442440449 // Division (quotient) val quotient = a / b println("Quotient: $quotient") // Output: Quotient: 4294967298 // Remainder val remainder = a % b println("Remainder: $remainder") // Output: Remainder: 1 // Quotient and Remainder together val divRem = a divrem b println("Quotient: ${divRem.quotient}, Remainder: ${divRem.remainder}") // Output: Quotient: 4294967298, Remainder: 1 // Exponentiation val power = BigInteger.fromInt(2).pow(100) println("2^100: $power") // Output: 2^100: 1267650600228229401496703205376 ``` -------------------------------- ### Gradle Dependency for KotlinX Serialization Source: https://github.com/ionspin/kotlin-multiplatform-bignum/blob/main/bignum-serialization-kotlinx/README.md Add this dependency to your Gradle build file to enable BigInteger and BigDecimal serialization with KotlinX Serialization. ```kotlin implementation("com.ionspin.kotlin:bignum-serialization-kotlinx:0.3.2") ``` -------------------------------- ### Create BigInteger from String Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigInteger-Usage-Overview Use `BigInteger.parse` to create a BigInteger from a string representation in a specified base. Ensure the string is valid for the given base. ```kotlin BigInteger.parse("-1122334455667788990011223344556677889900", 10) ``` -------------------------------- ### Convert Long/Int/Short/Byte to BigDecimal using extension functions Source: https://github.com/ionspin/kotlin-multiplatform-bignum/blob/main/README.md Use the `toBigDecimal()` extension function to convert primitive numeric types like Long, Int, Short, and Byte to BigDecimal. This ensures type safety and precision. ```kotlin val bigDecimalFromLong = 10.toLong().toBigDecimal() val bigDecimalFromInt = 10.toInt().toBigDecimal() val bigDecimalFromShort = 10.toShort().toBigDecimal() val bigDecimalFromByte = 10.toByte().toBigDecimal() ``` -------------------------------- ### Convert String to BigInteger Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigDecimal-Usage-Overview Use the toBigInteger extension property on a String. ```kotlin val bigDecimal = "12345678.123".toBigInteger ``` -------------------------------- ### BigInteger Division (Remainder) Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigInteger-Usage-Overview Obtain the remainder of a BigInteger division using the `%` operator. This is useful in modular arithmetic and when the exact result of division is needed. ```kotlin val a = BigInteger.fromLong(Long.MAX_VALUE) val b = BigInteger.fromInt(Int.MAX_VALUE) val dividend = a + b val divisor = BigInteger.fromLong(Long.MAX_VALUE) val remainder = dividend % divisor println("Remainder: $remainder") ``` -------------------------------- ### BigDecimal Extension Functions for Primitive Types Source: https://context7.com/ionspin/kotlin-multiplatform-bignum/llms.txt Demonstrates arithmetic operations between Kotlin primitive types (Double, Float, Long) and BigDecimal using extension functions. This enables precise calculations with decimal numbers. ```kotlin import com.ionspin.kotlin.bignum.integer.BigInteger import com.ionspin.kotlin.bignum.integer.toBigInteger import com.ionspin.kotlin.bignum.decimal.BigDecimal import com.ionspin.kotlin.bignum.decimal.toBigDecimal // BigDecimal extensions val bigDec = BigDecimal.parseString("100.5") val decSum = 50.5 + bigDec // Double + BigDecimal val decDiff = 200.0f - bigDec // Float - BigDecimal val decProduct = 2L * bigDec // Long * BigDecimal println("50.5 + 100.5 = ${decSum.toStringExpanded()}") // 151 println("200.0 - 100.5 = ${decDiff.toStringExpanded()}") // 99.5 println("2 * 100.5 = ${decProduct.toStringExpanded()}") // 201 ``` -------------------------------- ### BigInteger Human-Readable Serialization Source: https://github.com/ionspin/kotlin-multiplatform-bignum/blob/main/bignum-serialization-kotlinx/README.md Serializes BigInteger values into a human-readable string format. This is convenient but may be slower than array-based serialization. ```kotlin @Serializable data class BigIntegerHumanReadableSerializtionTestData(@Contextual val a : BigInteger, @Contextual val b : BigInteger) val a = BigInteger.parseString("-1000000000000000000000000000002000000000000000000000000000003") val b = BigInteger.parseString("1000000000000000000000000000002000000000000000000000000000003") val testObject = BigIntegerHumanReadableSerializtionTestData(a, b) val json = Json { serializersModule = bigIntegerhumanReadableSerializerModule } val serialized = json.encodeToString(testObject) println(serialized) result: {"a":"-1000000000000000000000000000002000000000000000000000000000003","b":"1000000000000000000000000000002000000000000000000000000000003"} ``` -------------------------------- ### BigDecimal Human-Readable Serialization Source: https://github.com/ionspin/kotlin-multiplatform-bignum/blob/main/bignum-serialization-kotlinx/README.md Serializes BigDecimal values into a human-readable string format. This is useful for readability but may impact performance. ```kotlin @Serializable data class BigDecimalHumanReadableTestData(@Contextual val a : BigDecimal, @Contextual val b : BigDecimal) val a = BigDecimal.parseString("1.000000000020000000000300000000004") val b = BigDecimal.parseString("-1.000000000020000000000300000000004") val testObject = BigDecimalHumanReadableTestData(a, b) val json = Json { serializersModule = bigDecimalHumanReadableSerializerModule } val serialized = json.encodeToString(testObject) println(serialized) result: {"a":"1.000000000020000000000300000000004","b":"-1.000000000020000000000300000000004"} ``` -------------------------------- ### Convert BigDecimal to Other Types Source: https://context7.com/ionspin/kotlin-multiplatform-bignum/llms.txt Convert BigDecimal instances to strings, BigIntegers, or primitive types, and manipulate decimal point placement. ```kotlin import com.ionspin.kotlin.bignum.decimal.BigDecimal val decimal = BigDecimal.parseString("1234.5678") // String representations println("Scientific notation: $decimal") // Output: 1.2345678E+3 println("Expanded notation: ${decimal.toStringExpanded()}") // Output: 1234.5678 println("Plain string: ${decimal.toPlainString()}") // Output: 1234.5678 // Convert to BigInteger (truncates decimal part) val bigInt = decimal.toBigInteger() println("As BigInteger: $bigInt") // Output: 1234 // Convert to primitive types val asLong = decimal.longValue(exactRequired = false) val asDouble = decimal.doubleValue(exactRequired = false) println("As Long: $asLong") // 1234 println("As Double: $asDouble") // 1234.5678 // Check if whole number val isWhole = decimal.isWholeNumber() println("Is whole number: $isWhole") // false // Move decimal point val moved = decimal.moveDecimalPoint(2) println("Moved 2 places right: ${moved.toStringExpanded()}") // Output: 123456.78 ``` -------------------------------- ### BigInteger Addition Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigInteger-Usage-Overview Perform addition on BigIntegers using the `+` operator. This is suitable for summing large numbers that exceed the capacity of standard integer types. ```kotlin val a = BigInteger.fromLong(Long.MAX_VALUE) val b = BigInteger.fromInt(Integer.MAX_VALUE) val sum = a + b println("Sum: $sum") ``` -------------------------------- ### Create BigDecimal from Long with Exponent Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigDecimal-Usage-Overview Create a BigDecimal from a Long value treated as scientific notation with a specified exponent. ```kotlin val bigDecimal = BigDecimal.fromLongWithExponent(1, (-5).toBigInteger()) println("BigDecimal: $bigDecimal") println("BigDecimalExpanded: ${bigDecimal.toStringExpanded()}") ``` -------------------------------- ### Format BigDecimal as Expanded String Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigDecimal-Usage-Overview Convert a BigDecimal to its expanded string representation instead of the default scientific notation. ```kotlin val bigDecimal = BigDecimal.parseString("123.456") println("BigDecimal: ${bigDecimal.toStringExpanded()}") bigDecimal.toStringExpanded() == "123.456" ``` -------------------------------- ### Round BigNum to Specific Digit Precision Source: https://github.com/ionspin/kotlin-multiplatform-bignum/blob/main/README.md Demonstrates `roundToDigitPosition` for rounding a BigNum to a specific digit precision, irrespective of the decimal point's location, using a specified rounding mode. ```kotlin assertTrue { val rounded = BigDecimal.parseString("1234.5678") .roundToDigitPosition(3, RoundingMode.ROUND_HALF_TOWARDS_ZERO) rounded.toStringExpanded() == "1230" } assertTrue { val rounded = BigDecimal.parseString("0.0012345678") .roundToDigitPosition(4, RoundingMode.ROUND_HALF_TOWARDS_ZERO) rounded.toStringExpanded() == "0.001" } ``` -------------------------------- ### BigInteger AND Operation Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigInteger-Usage-Overview Apply a bitwise AND operation between two BigIntegers using the `and` operator. This is commonly used for masking bits or checking specific bit patterns. ```kotlin val operand = BigInteger.parseString("FFFFFFFFFF000000000000", 16) val mask = BigInteger.parseString("00000000FFFF0000000000", 16) val andResult = operand and mask println("And result: ${andResult.toString(16)}") ``` -------------------------------- ### BigInteger OR Operation Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigInteger-Usage-Overview Perform a bitwise OR operation between two BigIntegers using the `or` operator. This is useful for setting specific bits or combining bit patterns. ```kotlin val operand = BigInteger.parseString("FFFFFFFFFF000000000000", 16) val mask = BigInteger.parseString("00000000FFFF0000000000", 16) val orResult = operand or mask println("Or result: ${orResult.toString(16)}") ``` -------------------------------- ### Perform BigInteger Bitwise Operations in Kotlin Source: https://context7.com/ionspin/kotlin-multiplatform-bignum/llms.txt Execute bitwise operations such as left shift (`shl`), right shift (`shr`), XOR (`xor`), AND (`and`), OR (`or`), and NOT (`not`) on BigInteger values. Ensure correct base is used when converting results to string. ```kotlin import com.ionspin.kotlin.bignum.integer.BigInteger // Shift left val shiftedLeft = BigInteger.fromByte(1) shl 215 println("1 << 215: $shiftedLeft") // Output: 52656145834278593348959013841835216159447547700274555627155488768 // Shift right val large = BigInteger.parseString("100000000000000000000000000000000", 10) val shiftedRight = large shr 90 println("Shifted right by 90: $shiftedRight") // Output: 80779 // XOR operation val operand = BigInteger.parseString("11110000", 2) val mask = BigInteger.parseString("00111100", 2) val xorResult = operand xor mask println("XOR result: ${xorResult.toString(2)}") // Output: 11001100 // AND operation val andOperand = BigInteger.parseString("FFFFFFFFFF000000000000", 16) val andMask = BigInteger.parseString("00000000FFFF0000000000", 16) val andResult = andOperand and andMask println("AND result: ${andResult.toString(16)}") // Output: ff000000000000 // OR operation val orResult = andOperand or andMask println("OR result: ${orResult.toString(16)}") // Output: ffffffffffff0000000000 // NOT (bitwise inversion) val notOperand = BigInteger.parseString("11110000", 2) val notResult = notOperand.not() println("NOT result: ${notResult.toString(2)}") // Output: 1111 ``` -------------------------------- ### BigInteger Multiplication Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigInteger-Usage-Overview Multiply BigIntegers using the `*` operator. This is essential for calculations involving products of large numbers where overflow would occur with standard types. ```kotlin val a = BigInteger.fromLong(Long.MAX_VALUE) val b = BigInteger.fromLong(Long.MIN_VALUE) val product = a * b println("Product: $product") ``` -------------------------------- ### BigInteger Shift Right Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigInteger-Usage-Overview Execute a right bit shift operation on a BigInteger using the `shr` operator. This is equivalent to integer division by powers of 2. ```kotlin val a = BigInteger.parseString("100000000000000000000000000000000", 10) val shifted = a shr 90 ``` -------------------------------- ### Round BigNum to Specific Decimal Position Source: https://github.com/ionspin/kotlin-multiplatform-bignum/blob/main/README.md Illustrates the use of `roundToDigitPositionAfterDecimalPoint` to round a BigNum to a specified number of digits after the decimal point using a given rounding mode. ```kotlin assertTrue { val rounded = BigDecimal.fromIntWithExponent(123456789, 3) .roundToDigitPositionAfterDecimalPoint(3, RoundingMode.CEILING) rounded.toStringExpanded() == "1234.568" } ``` -------------------------------- ### BigDecimal Array-Based Serialization Source: https://github.com/ionspin/kotlin-multiplatform-bignum/blob/main/bignum-serialization-kotlinx/README.md Serializes BigDecimal values using an array-based format, which is typically more performant than human-readable serialization. ```kotlin val a = BigDecimal.parseString("1.000000000020000000000300000000004") val b = BigDecimal.parseString("-1.000000000020000000000300000000004") val testObject = BigDecimalArraySerializtionTestData(a, b) val json = Json { serializersModule = bigDecimalArraySerializerModule } val serialized = json.encodeToString(testObject) println(serialized) result: {"a":{"significand":{"magnitude":[7819074433982969860,108420217250718],"sign":"POSITIVE"},"exponent":0},"b":{"significand":{"magnitude":[7819074433982969860,108420217250718],"sign":"NEGATIVE"},"exponent":0}} ``` -------------------------------- ### BigInteger Array Serialization Source: https://github.com/ionspin/kotlin-multiplatform-bignum/blob/main/bignum-serialization-kotlinx/README.md Serializes BigInteger values using an array-based format. This is generally faster than human-readable serialization. ```kotlin @Serializable data class BigIntegerArraySerializtionTestData(@Contextual val a : BigInteger, @Contextual val b : BigInteger) val a = BigInteger.parseString("-1000000000000000000000000000002000000000000000000000000000003") val b = BigInteger.parseString("1000000000000000000000000000002000000000000000000000000000003") val testObject = BigIntegerHumanReadableSerializtionTestData(a, b) val json = Json { serializersModule = bigIntegerArraySerializerModule } val serialized = json.encodeToString(testObject) println(serialized) result: {"a":{"magnitude":[2083438008362598403,3369964156491764979,4367533269890700295,1274],"sign":"NEGATIVE"},"b":{"magnitude":[2083438008362598403,3369964156491764979,4367533269890700295,1274],"sign":"POSITIVE"}} ``` -------------------------------- ### Convert BigInteger to and from big-endian byte array Source: https://github.com/ionspin/kotlin-multiplatform-bignum/blob/main/README.md Use `toByteArray()` to convert a BigInteger to a big-endian byte array and `fromByteArray()` to reconstruct it. This is useful for serialization or interoperability. ```kotlin val bigIntOriginal = BigInteger.fromULong(ULong.MAX_VALUE) val byteArray = bigIntOriginal.toByteArray() val reconstructed = BigInteger.fromByteArray(byteArray) println("${bigIntOriginal == reconstructed}") ``` -------------------------------- ### Convert Float or Double to BigDecimal Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigDecimal-Usage-Overview Use the toBigDecimal extension function on floating point types. ```kotlin val bigDecimalFromFloat = 123.456f.toBigDecimal() val bigDecimalFromDouble = 123.456.toBigDecimal() ``` -------------------------------- ### Convert byte array to BigInteger using two's complement Source: https://github.com/ionspin/kotlin-multiplatform-bignum/blob/main/README.md Use `fromTwosComplementByteArray()` to create a BigInteger from a byte array representing a two's complement number. This is compatible with Java's BigInteger representation. ```kotlin val negativeInput = ubyteArrayOf(0xFFU, 0x55U, 0x44U, 0x34U) val negativeBigInt = BigInteger.fromTwosComplementByteArray(negativeInput.asByteArray()) ``` -------------------------------- ### Define DecimalMode Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigDecimal-Usage-Overview Configure precision and rounding behavior for arithmetic operations. ```kotlin data class DecimalMode(val decimalPrecision : Long = 0, val roundingMode : RoundingMode = RoundingMode.NONE) ``` -------------------------------- ### Create BigDecimal from Long Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigDecimal-Usage-Overview Convert a standard Long type to a BigDecimal. ```kotlin val bigDecimal = BigDecimal.fromLong(7111) println("BigDecimal: $bigDecimal") ``` -------------------------------- ### Throw exception for non-terminating results Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigDecimal-Architecture-and-Implementation Logic to detect and throw an exception when a division operation does not terminate. ```kotlin if (divRem.remainder != BigInteger.ZERO) { throw ArithmeticException("Non-terminating result of division operation " + "(i.e. 1/3 = 0.3333... library needs to know when to stop and how to round up at that point). " + "Specify decimalPrecision inside your decimal mode.") } ``` -------------------------------- ### BigInteger Shift Left Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigInteger-Usage-Overview Perform a left bit shift operation on a BigInteger using the `shl` operator. This is equivalent to multiplying the number by powers of 2. ```kotlin val a = BigInteger.fromByte(1) val shifted = a shl 215 println("Shifted: $shifted") ``` -------------------------------- ### Perform bitwise NOT operation on BigInteger Source: https://github.com/ionspin/kotlin-multiplatform-bignum/blob/main/README.md The `not()` method performs a bitwise inversion, returning the bitwise complement of the BigInteger. This differs from Java's two's complement inversion. ```kotlin val operand = BigInteger.parseString("11110000", 2) val result = operand.not() println("Not operation result: ${result.toString(2)}") ``` -------------------------------- ### Convert BigInteger to two's complement byte array Source: https://github.com/ionspin/kotlin-multiplatform-bignum/blob/main/README.md Use `toTwosComplementByteArray()` to convert a BigInteger, including negative numbers, into a two's complement byte array. This format is compatible with Java's BigInteger. ```kotlin val negativeBigInt = BigInteger.parseString("-AABBCC", 16) val negativeBigIntArray = negativeBigInt.toTwosComplementByteArray() ``` -------------------------------- ### BigInteger XOR Operation Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigInteger-Usage-Overview Perform a bitwise XOR operation between two BigIntegers using the `xor` operator. This is useful in various algorithms, including cryptography and data manipulation. ```kotlin val operand = BigInteger.parseString("11110000", 2) val mask = BigInteger.parseString("00111100", 2) val xorResult = operand xor mask println("Xor result: ${xorResult.toString(2)}") ``` -------------------------------- ### BigInteger Extension Functions for Primitive Types Source: https://context7.com/ionspin/kotlin-multiplatform-bignum/llms.txt Utilizes extension functions to perform arithmetic operations between Kotlin primitive types (Long, Int, Short) and BigInteger. This allows for seamless interoperability without explicit type conversions. ```kotlin import com.ionspin.kotlin.bignum.integer.BigInteger import com.ionspin.kotlin.bignum.integer.toBigInteger import com.ionspin.kotlin.bignum.decimal.BigDecimal import com.ionspin.kotlin.bignum.decimal.toBigDecimal // BigInteger extensions val bigInt = BigInteger.fromLong(1000) // Primitives can be used directly with BigInteger val sum = 500L + bigInt // Long + BigInteger val diff = 2000 - bigInt // Int - BigInteger val product = 3.toShort() * bigInt // Short * BigInteger val quotient = 5000L / bigInt // Long / BigInteger val remainder = 5500L % bigInt // Long % BigInteger println("500 + 1000 = $sum") // 1500 println("2000 - 1000 = $diff") // 1000 println("3 * 1000 = $product") // 3000 println("5000 / 1000 = $quotient") // 5 println("5500 % 1000 = $remainder") // 500 ``` -------------------------------- ### Define DecimalMode for BigNum Operations Source: https://github.com/ionspin/kotlin-multiplatform-bignum/blob/main/README.md Defines the DecimalMode data class used to control precision and rounding for BigNum operations. It includes properties for decimal precision, rounding mode, and scale. ```kotlin data class DecimalMode(val decimalPrecision : Long = 0, val roundingMode : RoundingMode = RoundingMode.NONE, val scale: Long = -1) ``` -------------------------------- ### BigInteger Subtraction Source: https://github.com/ionspin/kotlin-multiplatform-bignum/wiki/BigInteger-Usage-Overview Subtract BigIntegers using the `-` operator. This operation is useful for calculating differences between very large or very small numbers. ```kotlin val a = BigInteger.fromLong(Long.MIN_VALUE) val b = BigInteger.fromLong(Long.MAX_VALUE) val difference = a - b println("Difference: $difference") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.