1
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?

MySQL の UNSIGNED BIGINT の最大値を Ruby のビット演算で求める方法

Last updated at Posted at 2025-02-18

この記事は?

MySQL :: MySQL 8.4 Reference Manual :: 13.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT

上記のページによると、MySQL の UNSIGNED BIGINT を格納する領域は 8 bytes で、最大値は $2^{64}-1$ です。この最大値を Ruby で求める方法を残しておきます。

方法

以下の 2 つの方法で求められます。上の方法は $2^{64}-1$ をそのまま Ruby で計算しただけです。今回は下の方法について詳しく解説します。

2**64 - 1
#=> 18446744073709551615

(1 << 64) - 1
#=> 18446744073709551615

UNSIGNED BIGINT を格納する領域は 8 bytes です。これは bit に直すと 8 bytes * 8 = 64 bits です。

Integer#<< を使用して 1 を 64 bits 左にシフトします。この << はビット演算に慣れていない場合はよくわからない処理に見えるかもしれませんが、適宜 to_s(2) で 10 進数を 2 進数に変換しながら処理を追ってみると、やっていることはとてもシンプルだと分かります。

# 10 進数の 1 を 2 進数に変換する。
1.to_s(2)
#=> "1"

# 1 を 64 bits 左にシフトする。
1 << 64
#=> 18446744073709551616

# 結果を 2 進数に変換すると、1 が 64 bits だけ左にずれていることが分かる。
(1 << 64).to_s(2)
#=> "10000000000000000000000000000000000000000000000000000000000000000"

# この 2 進数の桁数は 65 桁。
(1 << 64).to_s(2).size
#=> 65

ここから 1 を引けば、8 bytes (64 bits) の領域に格納できる最大の整数を求めることができます。

(1 << 64) - 1
#=> 18446744073709551615

# この 2 進数はすべてのビットが 1 であり、桁数は 64 桁。つまり 64 bits で表現できる最大値。
((1 << 64) - 1).to_s(2)
#=> "1111111111111111111111111111111111111111111111111111111111111111"
((1 << 64) - 1).to_s(2).size
#=> 64

# 2**64 - 1 と一致する。
(1 << 64) - 1 == 2**64 - 1
#=> true
1
0
1

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
1
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?