1. 程式人生 > >java將一個數轉化為二進位制形式

java將一個數轉化為二進位制形式


import javax.swing.JOptionPane;

public class ErjinZhi {


public static void main(String[] args) {
// TODO Auto-generated method stub
int number = 8;
int num = 9;
byte b = 8;
int save;
String numm;
numm = Integer.toBinaryString(num);
int sum;
ErjinZhi bi = new ErjinZhi();


String result = "";

//方式一

for (int i = number; i >= 1; i /= 2) {


if (i % 2 == 0) {
sum = 0;
} else {
sum = 1;
}
result = sum + result;


}


System.out.println(result);

//方式二

for (int i = 0; i < 9; i++) {
byte j = (byte) (b & (1 << 8 - i));
char c = j == 0 ? '0' : '1';
System.out.print(c);
}
System.out.println();
bi.Binary(number);


/*
* save = num << 2; System.out.println(save);

* save = 7 & 4; System.out.println(save);
*/
}

//方式三
public void Binary(int num) {
for (int i = 31; i >= 0; i--) {
System.out.print(num >> i & 1);
}
}


}