Skip to content

Commit

Permalink
Add toBytes proc
Browse files Browse the repository at this point in the history
  • Loading branch information
ehmry committed Jun 19, 2023
1 parent f0ddda5 commit eca7a52
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion src/bigints.nim
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
##
## The bitwise operations behave as if negative numbers were represented in 2's complement.

import std/[algorithm, bitops, math, options]
import std/[algorithm, bitops, endians, math, options]

type
BigInt* = object
Expand Down Expand Up @@ -1304,3 +1304,26 @@ func powmod*(base, exponent, modulus: BigInt): BigInt =
result = (result * basePow) mod modulus
basePow = (basePow * basePow) mod modulus
exponent = exponent shr 1

proc toBytes*(a: BigInt; endianness = system.cpuEndian): seq[byte] =
## Convert a `BigInt` to a byte-sequence.
## The byte-sequence *does not* include a sign-bit.
if not a.isZero:
result = newSeq[byte](a.limbs.len shl 2)
var i: int
case endianness
of bigEndian:
for s in [24, 16, 8, 0]:
result[i] = uint8(a.limbs[a.limbs.high] shr s)
if result[0] != 0x00: inc(i)
for l in countdown(a.limbs.high.pred, a.limbs.low):
bigEndian32(addr result[i], unsafeAddr a.limbs[l])
inc(i, 4)
result.setLen(i)
of littleEndian:
for l in 0..a.limbs.high:
littleEndian32(addr result[i], unsafeAddr a.limbs[l])
inc(i, 4)
while result[pred i] == 0x00:
dec i
result.setLen(i)

0 comments on commit eca7a52

Please sign in to comment.