forked from votingworks/electionguard-kotlin-multiplatform
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Make BigInteger.toByteArray compatible with java.math.BigInteger for …
…negative numbers
- Loading branch information
1 parent
b06c2a8
commit 7266f24
Showing
2 changed files
with
72 additions
and
1 deletion.
There are no files selected for viewing
43 changes: 43 additions & 0 deletions
43
egklib-core/src/commonTest/kotlin/electionguard/core/BigIntegerCompatibilityTest.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
package electionguard.core | ||
|
||
import electionguard.core.Base16.toHex | ||
import kotlin.test.Test | ||
import kotlin.test.assertEquals | ||
|
||
class BigIntegerCompatibilityTest { | ||
|
||
/** Since java.math.BigInteger uses two's complement with sign extension, | ||
* and javascript bigint not, we have to test proper conversion*/ | ||
@Test | ||
fun testBigIntToByteArray() { | ||
// Positive numbers | ||
var bi = BigInteger("1") | ||
assertEquals(byteArrayOf(1).toHex(), bi.toByteArray().toHex()) | ||
|
||
bi = BigInteger("127") | ||
assertEquals(byteArrayOf(0x7F).toHex(), bi.toByteArray().toHex()) | ||
|
||
bi = BigInteger("128") | ||
assertEquals(byteArrayOf(0x00, 0x80.toByte()).toHex(), bi.toByteArray().toHex()) | ||
|
||
bi = BigInteger("256") | ||
assertEquals(byteArrayOf(0x01, 0x00).toHex(), bi.toByteArray().toHex()) | ||
|
||
// Negative numbers | ||
bi = BigInteger("-1") | ||
assertEquals(byteArrayOf(0xFF.toByte()).toHex(), bi.toByteArray().toHex()) | ||
|
||
bi = BigInteger("-128") | ||
assertEquals(byteArrayOf(0x80.toByte()).toHex(), bi.toByteArray().toHex()) | ||
|
||
bi = BigInteger("-129") | ||
assertEquals(byteArrayOf(0xFF.toByte(), 0x7F).toHex(), bi.toByteArray().toHex()) | ||
|
||
bi = BigInteger("-256") | ||
assertEquals(byteArrayOf(0xFF.toByte(), 0x00).toHex(), bi.toByteArray().toHex()) | ||
|
||
// Zero | ||
bi = BigInteger("0") | ||
assertEquals(byteArrayOf(0x00).toHex(), bi.toByteArray().toHex()) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters