JAVA利用位移进行进制转换

class TransDemo
{
 public static void main(String[] args)
 {
  int a = 8152936;
  String res1 = toBin(a);
  String res2 = toBa(a);
  String res3 = toHex(a);
  System.out.println(res1 + "\n" + res2 + "\n" + res3);
 }

 
 //十进制->二进制
 public static String toBin(int num)
 {
  return trans(num, 1, 1);
 }

 
 //十进制->八进制

 public static String toBa(int num)
 {
  return trans(num, 7, 3);
 }

 
 //十进制->十六进制
 
 public static String toHex(int num)
 {
  return trans(num, 15, 4);
 }

 private static String trans(int num, int base, int offset)
 {
  char [] table = {'0', '1', '2', '3', '4', '5',
      '6', '7', '8', '9', 'A', 'B',
      'C', 'D', 'E', 'F'};
  char [] arr = new char[32];
  int pos = arr.length;
  while (num != 0)
  {
   int x = num & base;
   arr[--pos] = table[x];
   num = num >>> offset;
  }
  return arrayToString(arr, pos);
 }

 private static String arrayToString(char[] arr,int pos)
 {
  String s = "";
  for (int x = pos; x < arr.length; x++)
  {
   s = s + arr[x];
  }
  return s;
 }

}

你可能感兴趣的:(JAVA利用位移进行进制转换)