Java练习(6)——十进制转换为2、16进制

来源:互联网 发布:英雄联盟官方代练 知乎 编辑:程序博客网 时间:2024/05/22 17:12
/* 需求:将10进制转换为2进制,16进制; */public class toBin{public static void main(String[] args){tobin(25);tohex1(253);tohex2(253);tohex3(253);tohex3(253);}//二进制子函数static void tobin(int num){StringBuffer sb =new StringBuffer();while(num>0){sb.append(num%2);num/=2;}System.out.println(sb.reverse());}/* 16进制子函数(方法1):用除16模16,容器储存,再用if语句转换 */static void tohex1(int num){StringBuffer sb =new StringBuffer();while(num>0){int temp=num%16;//if语句改变10以上的数为A、B、····if(temp>9)sb.append((char)(temp-10+'A'));else sb.append(temp);num/=16;}System.out.println(sb.reverse());}/* 16进制子函数(方法2):位运算思想 */static void tohex2(int num){StringBuffer sb =new StringBuffer();while(num>0)//或者for(int i=0;i<8;i++)这样在数之前有0{int temp=num&15;if(temp>9)sb.append((char)(temp-10+'A'));else sb.append(temp);num=num>>>4;//进入下次循环}System.out.println(sb.reverse());}/* 16进制子函数(方法3):不用if,用数组查表法 */static void tohex3(int num){StringBuffer sb =new StringBuffer();while(num>0){int temp=num%16;char []arry1= {'0','1','2','3','4','5','6','7','8','9',         'A','B','C','D','E','F'};sb.append(arry1[temp]);num/=16;}System.out.println(sb.reverse());}}

原创粉丝点击