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?

ビット演算を利用すると 1 つの整数値で複数の属性を表現できる

Last updated at Posted at 2024-11-02

内容

ビット演算を利用すると 1 つの整数値で複数の属性を表現できて便利です :wink:

# 整数を 2 進数の文字列に変換するメソッドを定義する。
using (Module.new do
  refine Integer do
    def to_binary_string(digits = 4)
      to_s(2).then { "%0#{digits}d" % _1 }
    end
  end
end)

高血圧 = 1
高血糖 = 2
高コレステロール = 4
高尿酸 = 8

高血圧.to_binary_string
#=> "0001"
高血糖.to_binary_string
#=> "0010"
高コレステロール.to_binary_string
#=> "0100"
高尿酸.to_binary_string
#=> "1000"

太郎 = 2
太郎.to_binary_string
#=> "0010"
太郎.anybits?(高血圧)
#=> false
太郎.anybits?(高血糖)
#=> true
太郎.anybits?(高コレステロール)
#=> false
太郎.anybits?(高尿酸)
#=> false

二郎 = 11
二郎.to_binary_string
#=> "1011"
二郎.anybits?(高血圧)
#=> true
二郎.anybits?(高血糖)
#=> true
二郎.anybits?(高コレステロール)
#=> false
二郎.anybits?(高尿酸)
#=> true

参考

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?