#!/usr/bin/ruby -Ke

# ===============================
# Bit Operate Library
# based on libbitstr.rb(in xjpp) by tokuhisa
# Reference: http://www.nminoru.jp/~nminoru/programming/bitcount.html
# Version 1.0
# 2004/12/15
# Keichiro Katayama
# ===============================

class Integer

  # 1の個数を数える
  def num_of_bits1()
    num = 0
    bitmap = self
    while( bitmap != 0 ) do
      bitmap = bitmap & (bitmap - 1)
      num += 1
    end
    return num
  end

  # 0番目からSelf番目までのビットをすべて1にした数値を返す。
  def fill_bits1()
    if self == 0 then
      return 0
    end
    return ( 1 << self ) -1
  end
  
  # Get Number of Training Zero (NTZ)
  def num_of_training_zero
    if self == 0 then
      raise Exception, "There is no NTZ!"
    end
    return ( ( ~ self ) & ( self - 1 ) ).num_of_bits1
  end
  alias :ntz :num_of_training_zero

  # NTZから1が連続する個数を返す。
  def num_of_continuous_bits1_from_ntz
     ( ~ ( self >> self.num_of_training_zero ) ).num_of_training_zero
  end

end

