0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Julia: BigIntがらみのコツのメモ

Last updated at Posted at 2021-10-04

JuliaのBigIntがらみのコツをまとめた自分用メモ。

BigIntと文字列表現との相互変換

整数と文字列表現との相互変換は、↓にまとめられている。

その方法は、BigIntでも基本的に使える。

BigIntとBitArrayとの相互変換

BigIntをBitArrayに変換

下記は、BigIntに限らず、通常の整数にも使える。

例: x::BigIntをBitArrayに変換。ビット数は、xを表現するのに必要十分なビット数になる。

BitArray(digits(x,base=2))

例: x::BigIntをBitArrayに変換。ビット数を256に指定する。xが小さい値の場合、上位ビットが0で埋められる。

BitArray(digits(x,base=2,pad=256))

注: 戻り値をar::BitArrayとしたとき、xの最下位ビットがar[1]、最上位ビットがar[end]としたビット配列になる。

BitArrayをBigIntに変換

変換するための標準の関数は用意されていないみたい。
自力で書く。
それでも大したことはない。

参考:
https://discourse.julialang.org/t/parse-an-array-of-bits-bitarray-to-an-integer/42361

例: BitArrayをBigIntに変換する関数to_bigint

to_bigint(ar::BitArray) = sum(((i, x),) -> big(x) << ((i-1) * 8sizeof(x)), enumerate(ar.chunks))

ビット単位ではなく、ar.chunksしてInt単位で変換しているので速い。

注: ar[1]を最下位ビット、ar[end]を最上位ビットとしたBigIntになる。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?