●
●
●
●
《最受欢迎的精准提升平台》
/**
*@Title: ${filename}
*@Package: ${package_name}
*@Description: ${todo}
*进制转换
市面上有两种不同的转换方式
对于正数来说,都是一样的
对于负数的处理上,不同,1)在线工具,是直接在前面加负号
2)计算机中的计算器却是使用补码进行转换的
十进制转二进制
十进制转十六进制
*
*@author: 源代码资料尽在"清哥好课堂"公众号:qghktit
*@date: ${date}${time}
*@version: 1.0
*/
public class BinaryConversion
{
public static void main(String[] args)
{
//查表法
char[] chHEX = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
//我们所求出的来t, 对应数组的下标值的空间里的内容
int num = -92;
char[] nRes = new char[64];
int nloc = nRes.length-1;
while (num != 0)
{
int t = num & 15; //补码
nRes[nloc] = chHEX[t];
nloc--;
num = num >>> 4;
}
//输出数组
for (int i=nloc+1; i<nRes.length; i++)
{
System.out.print(nRes[i]);
}
}
public static void main3(String[] args)
{
//十进制转十六进制
//二进制转十六进制的时候,每四位二进制,对应一位十六进制
//十六进制 有16个基数, 0--9 A B C D E F
int num = 92;
// int[] nRes = new int[64];
// int nloc = nRes.length-1;
char[] nRes = new char[64];
int nloc = nRes.length-1;
while (num != 0)
{
int t = num & 15; //补码
if (t > 9) //ABCDEF A+2 t-10 + 'A'
{
//System.out.print((char)(t-10+'A'));
nRes[nloc] = (char)(t-10+'A');
}
else // 0<=t<=9
{
//System.out.print(t+",");
nRes[nloc] = (char)('0'+t);
}
nloc--;
num = num >>> 4;
}
//输出数组
for (int i=nloc+1; i<nRes.length; i++)
{
System.out.print(nRes[i]);
}
}
public static void main2(String[] args)
{
//使用位运算
//右移 >>
//右移运算去做进制转换
// >>> 不管是负数还是正数,高位都补0
int num = -92;
int[] nRes = new int[32];
int nloc = nRes.length-1;
while (num != 0)
{
int t = num & 1;
//System.out.print(t +",");
nRes[nloc--] = t; //nRes[nloc--]=t 相当于nRes[nloc]=t; nloc--;
//移位
num = num >>>1;
}
//输出数组
for (int i=nloc+1; i<nRes.length; i++)
{
System.out.print(nRes[i]);
}
// //第一次
// int t = num &1; // 0 余数
// System.out.print(t +",");
// //移位
// num = num >> 1; //46
//
// //第二次
// t = num & 1; //0
// System.out.print(t +",");
// //移位
// num = num >> 1; //23
// //第三次
// t = num & 1; //1
// System.out.print(t +",");
// //移位
// num = num >> 1; //11
}
public static void main1(String[] args)
{
//92 --->0101 1100
//短除法
//对于一个32位的系统
int num = 92;
int[] nRes = new int[32];
int nloc = nRes.length-1; //用来记录余数应该要存储的位置
while (num != 0)
{
int t = num%2;
//System.out.print(t+",");
//直接把取的余数从数组的最后位置往前存储
//nRes[nRes.length-1]
nRes[nloc] = t;
nloc--;
num = num/2;
}
//输出数组
for (int i=nloc+1; i<nRes.length; i++)
{
System.out.print(nRes[i]);
}
// //第一次
// int t = num%2; // 0 = 92%2
// num = num / 2; // 46 = 92/2
//
// //第二次
// t = num%2; // 0 = 46%2
// num = num/2; //23 = 46/2
//
// //第三次
// t = num%2 ; // 1 = 23%2
// num = num/2; //11 = 23/2
//
// //到什么时候结束
// //0
// // num = 0
}
}
清哥好课堂公众号
微信号 : qghktit
新浪微博:清哥好课堂
联系客服