LoginSignup
4
4

More than 5 years have passed since last update.

rubyでビット文字列から'1'の位置を求める

Posted at

ビットの開始位置を右(右端を位置0)として。

scan_bits_index.rb
"10100100110".reverse.split('1',-1).inject([]){|ret,i| ret << i.size + (ret.last.nil? ? 0 : ret.last + 1); ret }[0..-2]
# => [1, 2, 5, 8, 10]

自分が必要だったのは左端から数えた位置だったので、ビットの開始位置を左から(左端を位置0)と考えるとこうなる。

scan_bits_index_from_left.rb
"10100100110".split('1',-1).inject([]){|ret,i| ret << i.size + (ret.last.nil? ? 0 : ret.last + 1); ret }[0..-2]
# => [0, 2, 5, 8, 9]
4
4
3

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