标签:buffer exti base string 综合 param char ringbuf style
import java.util.Scanner; public class TestTransform { public static void main(String[] args) { trans(); } // public static void toBin0(int num) { // trans(num, 2); // } // // public static void toOcto(int num) { // trans(num, 8); // } // // public static void toHex0(int num) { // trans(num, 16); // } /** * 十进制 --> 二、八、十六进制 综合版本 * * 由用户进行输入想要转换的数和进制 * * @param num * @param base * @param wei */ public static void trans() { System.out.println("请输入你要转换的十进制数和要转换的进制"); Scanner sc = new Scanner(System.in); int num = sc.nextInt(); int base = sc.nextInt(); int wei; if (num == 0) { System.out.println(0); sc.close(); return; } if (base == 2) { wei = 1; } else if (base == 8) { wei = 3; } else if (base == 16) { wei = 4; }else { sc.close(); return; } char[] chs = { ‘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 temp = num % base; arr[--pos] = chs[temp]; num = num >>> wei; } for (int i = pos; i < arr.length; i++) { System.out.print(arr[i]); } System.out.println(); sc.close(); } /** * 十进制 --> 二进制 */ public static void toBin(int i) { StringBuffer sBuffer = new StringBuffer(); while (i > 0) { sBuffer.append(i % 2); i = i / 2; } System.out.println(sBuffer.reverse());// reverse()方法将sBuffer倒置 } /** * 十进制 --> 十六进制 */ public static void toHex(int i) { StringBuffer sBuffer = new StringBuffer(); for (int j = 0; j < 8; j++) { int temp = i % 16;// 或者&15 if (temp > 9) { sBuffer.append((char) (temp - 10 + ‘A‘)); } else { sBuffer.append(temp); } i = i >>> 4; } System.out.println(sBuffer.reverse()); } /** * 查表法 十进制 --> 二进制 */ public static void toBin2(int num) { char[] chs = { ‘0‘, ‘1‘ }; char[] arr = new char[32]; int pos = arr.length; while (num != 0) { int temp = num % 2; arr[--pos] = chs[temp]; num = num >>> 1; } for (int i = pos; i < arr.length; i++) { System.out.print(arr[i]); } System.out.println(); } /** * 查表法 十进制 --> 十六进制 */ public static void toHex2(int num) { char[] chs = { ‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘, ‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘ }; char[] arr = new char[8]; int pos = arr.length; // pos 指针 while (num != 0) { int temp = num % 16; arr[--pos] = chs[temp]; num = num >>> 4; } for (int i = pos; i < arr.length; i++) { System.out.print(arr[i]); } } }
标签:buffer exti base string 综合 param char ringbuf style
原文地址:https://www.cnblogs.com/blogs-of-chg/p/9729612.html