十进制转二进制
方法一:
class arraytests
{
public static void main(String[]args)
{
tobin(6);
}
public static void tobin(int num)
{
while(num>0)
{
System.out.println(num&2)
num=num/2;
}
}
}
输出 011
若要输出110则需要做如下修改
public static void tobin(int num)
{
StringBuffer sb=new StringBuffer; //java特殊函数,装载数据
while(num>0)
{
sb.append(num%2)//添加num的值,储存到sb空间里
num=num/2;
}
System.out.println(sb.reverse()) //利用reverse转换顺序
}
方法二:十进制转为十六进制
public static void toHex(int num)
{
StringBuffer sb=new StringBuffer;
for (int x=0;i<8;i++)//i 可以从任意数开始,只要循环8次即可,因为一个数只占8个字节 例如60的二进制
0000-0000 0000-0000 0000-0000 0011-1100,对该数进行8次循环与运算,一次求得每四位的值,四
个二进制位代表一个十六进制位
{
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)
}
}
方法三 十进制转为十六进制
用查表法收集数据
0 1 2 3 4 5 6 7 8 9 10 A B C D E F 十六进制中的元素
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
查表法:将所有的元素临时储存起来,建立对应关系。每一次num&15后的值将作为索引去查询建立好的表,就可以
找到对应元素,比num-10+‘a'
可以通过数组来建立临时表
public static void to Hex(int num)
char[] chs={'1 ',' 2','3 ','4 ',
'4 ',' 5','6 ','7 ',
'8 ',' 9','A ','B ',
'C ',' D','E ','F ',
}
pos位操作数组的指针