10進数を2進数表記文字列へ変換するメソッド toBinaryDigit を作る。

ソースコード


public class IntegerTest {
 
  public static void main(String[] args) {
 
    int[] list = {
      Integer.MIN_VALUE, -16, -15, -3, -2, -1,
      0, 1, 2, 3, 15, 16, Integer.MAX_VALUE};
 
    for(int i=0;i <list.length; i++){
      test(list[i]);
    }
  }
 
  private static void test(int i){
    System.out.println(i + " -> " + toBinaryDigit(i));
  }
 
  // 10進数を2進数表記文字列へ変換するメソッド
  public static final String toBinaryDigit(int a){
    StringBuffer buf = new StringBuffer();
    for(int i=31; i>=0; i--){ // Javaのintは32ビット(4バイト)
      buf.append((a & (int)Math.pow(2,i)) >>> i);
    }
    return buf.toString();
  }
}

実行結果


-2147483648 -> 00000000000000000000000000000000
-16 -> 01111111111111111111111111110000
-15 -> 01111111111111111111111111110001
-3 -> 01111111111111111111111111111101
-2 -> 01111111111111111111111111111110
-1 -> 01111111111111111111111111111111
0 -> 00000000000000000000000000000000
1 -> 00000000000000000000000000000001
2 -> 00000000000000000000000000000010
3 -> 00000000000000000000000000000011
15 -> 00000000000000000000000000001111
16 -> 00000000000000000000000000010000
2147483647 -> 01111111111111111111111111111111

tags: zlashdot Java Java

Posted by NI-Lab. (@nilab)