一.将所求数字不断除以二,将余数存储起来,直到所求数字被除的结果为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; } } }