一.將所求數字不斷除以二,將餘數存儲起來,直到所求數字被除的結果爲1,最後將餘數倒轉後,就是 轉換後的二進制數。
package host; import java.util.Stack; public class Main { // TODO Auto-generated method stub public static void main (String[] args) { Stack<Integer> stack=new Stack<Integer>(); int a=405; while (a!=1) { int b=a%2; stack.push(b); a/=2; } while (!stack.isEmpty()) { System.out.print(stack.pop()); } } }
二.利用位運算進行二進制的轉換。
package host; public class Main { // TODO Auto-generated method stub public static void main (String[] args) { int a=5; a=a>>31; for (int i = 0; i <31; i--) { System.out.print(a&1); a=a<<1; } } }