0
0

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 5 years have passed since last update.

Crystal - BitArray

Last updated at Posted at 2015-08-31

Crystalの標準ライブラリのBitArrayクラスについて

概要

BitArrayは内部的にはBoolの配列です。
デフォルトはfalseでビット列が初期化され、
オプショナルでtrueに設定することも可能です。
BitArray#invertで全体を反転。
BitArray#toggle(index)で任意のビットを反転。

サンプル

プログラム

require "bit_array"
ba1 = BitArray.new(8)
pp ba1.to_s
ba1.invert
pp ba1.to_s
pp ba1.toggle(2)
pp ba1.to_s
pp ba1.toggle(2)
pp ba1.to_s

ba2 = BitArray.new(16, true)
pp ba2.to_s

ba1.each_with_index { |e, i|pp "#{i}: #{e}" }
converted = ba1.map_with_index { |e, i|i.odd? ? true : false }
pp converted

出力

ba1.to_s = "BitArray[00000000]"
ba1.to_s = "BitArray[11111111]"
ba1.toggle(2) = 4294967291
ba1.to_s = "BitArray[11011111]"
ba1.toggle(2) = 4294967295
ba1.to_s = "BitArray[11111111]"
ba2.to_s = "BitArray[1111111111111111]"
"#{i}: #{e}" = "0: true"
"#{i}: #{e}" = "1: true"
"#{i}: #{e}" = "2: true"
"#{i}: #{e}" = "3: true"
"#{i}: #{e}" = "4: true"
"#{i}: #{e}" = "5: true"
"#{i}: #{e}" = "6: true"
"#{i}: #{e}" = "7: true"
converted = [false, true, false, true, false, true, false, true]

GitHub

CrystalのBitArrayの実装が気になる方はこちら。

src/bit_arra.rb - crystal - GitHub

外部資料

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?