关于java十进制转变二进制,八进制,十六进制的不同方法及代码

关于java十进制转变二,八,十六的不同方法及代码

下面是我今天上午刚刚学习的,现在来总结并分享给大家,新手上路,如有不对多多指教
这也是我的第一篇博客,大二在校生一枚,初学java,一起进步。

1:十进制转变二进制

方法一:直接法

public static void tobin_1 (int a)
	{
		StringBuffer sb =new StringBuffer();
		
		while(a>0)
		{
			sb.append(a%2);
			a=a/2;
		}
		System.out.print(sb.reverse());
	}

方法二:查表法

public static void tobin_2 (int a)
	{
		char [] list={'0','1'};
		char[] arr=new char[32];
		int pa=0;
		while (a!=0)
		{
			int q=a&1;
			arr[pa++]=list[q];
			a=a>>>1;
		}
		for(int y=pa-1;y>=0;y--)
		{
			System.out.print(arr[y]);
		}		
	}

1:十进制转变十六进制

方法一:直接法(改进)

public static void tosl_1(int a)
	{
		StringBuffer sb =new StringBuffer();
		for (int x=0;x<8;x++)
		{
			int q=a & 15;
			if(q>9)
				sb.append((char)(q-10+'A'));
			else 
				sb.append(q);
			a = a >>> 4;
		}
		System.out.println(sb.reverse());
	}

方法二:直接法

public static void tosl_1(int a)
	{
		StringBuffer sb =new StringBuffer();
		for (int x=0;x<8;x++)
		{
			int q=a & 15;
			if(q>9)
				System.out.print((char)(q-10+'A'));
			else 
				System.out.print(q);
			a = a >>> 4;
		}
		System.out.println(sb.reverse());
	}

方法三:查表法

public static void tosl_2(int a)
	{
		char [] list={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
		int pa=0;
		char [] arr = new char [8];
		while (a!=0)
		{
			int b=a&15;
			arr[pa++]=list[b];
			
			a=a>>>4;
			
		}
		for(int y=pa-1;y>=0;y--)
		{
			System.out.print(arr[y]);
		}	
	}

转八进制也一样如此,不打了,下面来展示一下优化后的代码。
寻找几个代码的共性:数组arr[32]足够二进制,八进制及十六进制使用以及都要存入数组,移位,与一个数。
异性:它们所与,移,输入的数不一样。
可以得到如下优化代码

public static void qqq(int a,int x,int z)
//a:输入的数,x:所与的数,z:所移位数
	{
		char [] list={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
		int pa=0;//作为指针,做下标
		char [] arr = new char [32];
		while (a!=0)
		{
			int b=a&x;
			arr[pa++]=list[b];
			
			a=a>>>z;
			
		}
		for(int y=pa-1;y>=0;y--)
		{
			System.out.print(arr[y]);
		}	
		System.out.println(' ');
	}

然后进行函数的嵌套

//十进制——>二进制
	public static void tobin_3 (int a)
	{
		qqq(a, 1, 1);
	}
/十进制——>八进制
	public static void toba(int a)
	{
		qqq(a, 7, 3);
	}
//十进制——>十六进制
	public static void tosl_3(int a)
	{
		qqq(a, 15, 4);
	}

这样使函数更简洁。
新手文章,如有不足多多指教,一起进步

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章