一、十进制--二进制
String和StringBuffer他们都可以存储和操作字符串,即包含多个字符的字符串数据。
StringBuffer类的构造函数
public StringBuffer()
创建一个空的StringBuffer类的对象。
public StringBuffer( int length )
创建一个长度为 参数length 的StringBuffer类的对象。
注意:如果参数length小于0,将触发NegativeArraySizeException异常。
public StringBuffer( String str )
用一个已存在的字符串常量来创建StringBuffer类的对象。
public static void toBin(int num){StringBuffer sb = new StringBuffer(); //创建一个StringBuffer字符串变量while(num>0){//System.out.print(num%2);
sb.append(num%2);
StringBuffer append(boolean b)
|
这些方法都是向字符串缓冲区“追加”元素,但是,这个“元素”参数可以是布尔量、字符、字符数组、双精度数、浮点数、整型数、长整型数对象类型的字符串、字符串和StringBuffer类等。如果添加的字符超出了字符串缓冲区的长度,Java将自动进行扩充。
|
二、十进制--十六进【1】
public static void toHex(int num)
{
StringBuffer sb = new StringBuffer();
for(int i=0;i<8;i++)
{
int temp = num & 15;
if (temp>9)
{
sb.append((char)(temp-10+'A'));
//System.out.println((char)(temp-10+'A'));
}
else
{
//System.out.println(temp);
sb.append(temp);
}
num = num >>> 4; //右移4位
}
System.out.println(sb.reverse());
}
三、十进制->十六进制【2】
注:查表方式
//十进制->十六进制
public static void toHex2(int num)
{
char[] arr1 = new char[]{'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
char[] arr2 = new char[8];
for(int i=0; i<8; i++)
{
int temp = num & 15;
arr2[i]=arr1[temp];
num = num >>> 4; //右移4位
}
for(int i=arr2.length-1;i>=0;i--)
{
System.out.print(arr2[i]+",");
}
}
class ArrayTest7
{
public static void main(String[] args)
{
trans(60,16,4);
}
//1,15,7
/*
num代表要从十进制转换成二进制,或者八进制,或者十六进制的数。
base代表将要转化成的某进制。
offset表示多少为:二进制 1位,八进制 3位【7】,十六进制 4位【15】
*/
public static void trans(int num,int base,int offset)
{
char[] chs = {'0','1','2','3','4',
'5','6','7','8',
'9','A','B','C',
'D','E','F'};
base=base-1;
char[] arr = new char[32];
int pos = arr.length;
//二进制 1位 八进制 3位 十六进制 4位
while(num!=0)
{
int temp = num & base;
arr[--pos] = chs[temp];
num = num >>> offset;
}
for(int x=pos;x<arr.length;x++)
{
System.out.print(arr[x]);
}
System.out.println();
}
}