Skip to content

Instantly share code, notes, and snippets.

@holyshared
Last active June 14, 2017 01:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save holyshared/6605c96beddc7807a6f25eb6ddb00c69 to your computer and use it in GitHub Desktop.
Save holyshared/6605c96beddc7807a6f25eb6ddb00c69 to your computer and use it in GitHub Desktop.

OCamlでのbit演算

10進数38を2進数に変換すると100110になる。
これを16bitにするには、0埋めするので0000000000100110

指定のbit位置が1かどうか調べるにはlsl関数とland関数を使う。

lsl

lsl関数は左にビットシフトさせることができる。

1 lsl 0;; (* - : int = 1, 1を左に0ビットシフト *) 
1 lsl 1;; (* - : int = 2, 1を左に1ビットシフト *)
1 lsl 2;; (* - : int = 4, 1を左に2ビットシフト *)
1 lsl 3;; (* - : int = 8, 1を左に3ビットシフト *)

land

land関数は論理積を計算できる。

38 land 1;; (* - : int = 0, 1bit目 *)
38 land 2;; (* - : int = 2, 2bit目 *)
38 land 4;; (* - : int = 4, 3bit目 *)
38 land 8;; (* - : int = 0, 4bit目 *)
38 land 16;; (* - : int = 0, 5bit目 *)
38 land 32;; (* - : int = 32, 6bit目 *)

lsl && land

下記の例では10進数38のbit位置の状態を調べている。
0以外を返す場合、2進数の値は1になっている。

38 land (1 lsl 0);; (* - : int = 0 *)
38 land (1 lsl 1);; (* - : int = 2 *)
38 land (1 lsl 2);; (* - : int = 4 *)
38 land (1 lsl 3);; (* - : int = 0 *)
38 land (1 lsl 4);; (* - : int = 0 *)
38 land (1 lsl 5);; (* - : int = 32 *)
38 land (1 lsl 6);; (* - : int = 0 *)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment