1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Javaで「ビット演算子とシフト演算子」の動作を確認してみた

Posted at

概要

Javaで「ビット演算子とシフト演算子」の動作を確認してみました。
以下のページを参考にしました。

実装

以下のファイルを作成しました。

JSample8_1.java
class JSample8_1{
  public static void main(String[] args){
    int i1 = 85 & 15;
    int i2 = 85 | 15;
    int i3 = 85 ^ 15;
    int i4 = ~85;

    System.out.println("85 & 15 = " + i1);
    System.out.println("85 | 15 = " + i2);
    System.out.println("85 ^ 15 = " + i3);
    System.out.println("~85 = " + i4);
  }
}
JSample8_2.java
class JSample8_2{
  public static void main(String[] args){
    int i1 = 21 << 2;
    int i2 = 21 >> 2;
    int i3 = 21 >>> 2;

    System.out.println("21 << 2 = " + i1);
    System.out.println("21 >> 2 = " + i2);
    System.out.println("21 >>> 2 = " + i3);

    int i4 = -92 >> 2;
    int i5 = -92 >>> 2;

    System.out.println("-92 >> 2 = " + i4);
    System.out.println("-92 >>> 2 = " + i5);
  }
}

以下のコマンドを実行しました。

$ javac JSample8_1.java 
$ java JSample8_1 
85 & 15 = 5
85 | 15 = 95
85 ^ 15 = 90
~85 = -86
$ javac JSample8_2.java 
$ java JSample8_2 
21 << 2 = 84
21 >> 2 = 5
21 >>> 2 = 5
-92 >> 2 = -23
-92 >>> 2 = 1073741801

まとめ

何かの役に立てばと。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?