本文主要是介绍【Java】10进制和n进制互相转换,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
进制之间的转换,需要从最后一位入手;
① n进制 -> 10进制
基本思路:反序处理, 按位取次方求和;
② 10进制 -> n进制
基本思路:对商取余,反序处理;
可以试着分解一组10进制数字,就可以发现规律:
例:16进制数 "be6",对应的10进制为 "3046":
(需要格外注意余数 = 0的情况)
----------------------------------------------------------------------------
实际应用:
已知excel列号,获取列index:
/*** get column index by column address*/public static int getColumnIndexByAddress(String columnAddress) {int colNum = 0;for (int i = 0; i < columnAddress.length(); i++) {char ch = columnAddress.charAt(columnAddress.length() - 1 - i);colNum += (ch - 'A' + 1) * Math.pow(26, i);}return colNum - 1;}
已知列index,获取列号:
/*** get column address by column index*/public static String getColumnAddressByIndex(int columnIndex) {String colAddress = "";int quotient = columnIndex + 1;int remainder = 0;while (quotient > 0) {remainder = quotient % 26;if (remainder == 0) {colAddress += 'Z';quotient = quotient - 26;} else {colAddress += String.valueOf((char) (remainder - 1 + 'A'));}quotient = quotient / 26;}StringBuffer sb = new StringBuffer(colAddress);return sb.reverse().toString();}
这篇关于【Java】10进制和n进制互相转换的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!