[英]In Java how do you convert a decimal number to base 36?
如果我有一个十进制数,如何在 Java 中将其转换为基数 36?
给定一个数字i
,使用Integer.toString(i, 36)
。
See the documentation for Integer.toString请参阅 Integer.toString 的文档
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toString(int,%20int) http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toString(int,%20int)
toString
public static String toString(int i, int radix)
....
The following ASCII characters are used as digits:
0123456789abcdefghijklmnopqrstuvwxyz
What is radix
?什么是radix
? You're in luck for Base 36 (and it makes sense)你很幸运使用 Base 36(这是有道理的)
http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#MAX_RADIX http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#MAX_RADIX
public static final int MAX_RADIX 36
The following can work for any base, not just 36. Simply replace the String contents of code
.以下内容适用于任何基数,而不仅仅是 36。只需替换code
的 String 内容。
Encode:编码:
int num = 586403532;
String code = "0123456789abcdefghijklmnopqrstuvwxyz";
String text = "";
int j = (int)Math.ceil(Math.log(num)/Math.log(code.length()));
for(int i = 0; i < j; i++){
//i goes to log base code.length() of num (using change of base formula)
text += code.charAt(num%code.length());
num /= code.length();
}
Decode:解码:
String text = "0vn4p9";
String code = "0123456789abcdefghijklmnopqrstuvwxyz";
int num = 0;
int j = text.length();
for(int i = 0; i < j; i++){
num += code.indexOf(text.charAt(0))*Math.pow(code.length(), i);
text = text.substring(1);
}
First you have to convert your number it into the internal number format of Java (which happens to be 2-based, but this does not really matter here), for example by Integer.parseInt()
(if your number is an integer less than 2^31).首先,您必须将您的数字转换为 Java 的内部数字格式(恰好是基于 2 的,但这在这里并不重要),例如通过Integer.parseInt()
(如果您的数字是小于2^31)。 Then you can convert it from int
to the desired output format.然后您可以将其从int
转换为所需的输出格式。 The method Integer.toString(i, 36)
does this by using 0123456789abcdefghijklmnopqrstuvwxyz
as digits (the decimal digits 0-9 and lower case english letters in alphabetic order).方法Integer.toString(i, 36)
通过使用0123456789abcdefghijklmnopqrstuvwxyz
作为数字(十进制数字 0-9 和小写英文字母按字母顺序)来实现这一点。 If you want some other digits, you can either convert the result by replacing the "digits" (for example toUpperCase
), or do the conversion yourself - it is no magic, simply a loop of taking the remainder modulo 36 and dividing by 36 (with a lookup of the right digit).如果你想要一些其他数字,你可以通过替换“数字”(例如toUpperCase
)来转换结果,或者自己进行转换 - 这不是魔术,只是一个取余数模 36 并除以 36 的循环(查找正确的数字)。
If your number is longer than what int offers you may want to use long
(with Long
) or BigInteger
instead, they have similar radix-converters.如果您的数字比 int 提供的数字长,您可能想要使用long
(带Long
)或BigInteger
代替,它们具有类似的基数转换器。
If your number has "digits after the point", it is a bit more difficult, as most (finite) base-X-numbers are not exactly representable as (finite) base-Y-numbers if (a power of) Y is not a multiple of X.如果您的数字有“点后的数字”,那就有点困难了,因为如果 Y 的(幂)不是,则大多数(有限)基数 X 不能完全表示为(有限)基数 Y 数X 的倍数。
This code works:此代码有效:
public class Convert {
public static void main(String[] args) {
int num= 2147483647;
String text="ABCD1";
System.out.println("num: " + num + "=>" + base10ToBase36(num));
System.out.println("text: " +text + "=>" + base36ToBase10(text));
}
private static String codeBase36 = "0123456789abcdefghijklmnopqrstuvwxyz";
//"0123456789 abcdefghij klmnopqrst uvwxyz"
//"0123456789 0123456789 0123456789 012345"
private static String max36=base10ToBase36(Integer.MAX_VALUE);
public static String base10ToBase36(int inNum) {
if(inNum<0) {
throw new NumberFormatException("Value "+inNum +" to small");
}
int num = inNum;
String text = "";
int j = (int)Math.ceil(Math.log(num)/Math.log(codeBase36.length()));
for(int i = 0; i < j; i++){
text = codeBase36.charAt(num%codeBase36.length())+text;
num /= codeBase36.length();
}
return text;
}
public static int base36ToBase10(String in) {
String text = in.toLowerCase();
if(text.compareToIgnoreCase(max36)>0) {
throw new NumberFormatException("Value "+text+" to big");
}
if(!text.replaceAll("(\\W)","").equalsIgnoreCase(text)){
throw new NumberFormatException("Value "+text+" false format");
}
int num=0;
int j = text.length();
for(int i = 0; i < j; i++){
num += codeBase36.indexOf(text.charAt(text.length()-1))*Math.pow(codeBase36.length(), i);
text = text.substring(0,text.length()-1);
}
return num;
}
}
If you dont want to use Integer.toString(Num , base) , for instance, in my case which I needed a 64 bit long variable, you can use the following code: Using Lists in JAVA facilitates this conversion如果您不想使用 Integer.toString(Num , base) ,例如,在我需要一个 64 位长变量的情况下,您可以使用以下代码:在 JAVA 中使用列表有助于这种转换
long toBeConverted=10000; // example, Initialized by 10000
List<Character> charArray = new ArrayList<Character>();
List<Character> charArrayFinal = new ArrayList<Character>();
int length=10; //Length of the output string
long base = 36;
while(toBeConverted!=0)
{
long rem = toBeConverted%base;
long quotient = toBeConverted/base;
if(rem<10)
rem+=48;
else
rem+=55;
charArray.add((char)rem);
toBeConverted=quotient;
}
// make the array in the reverse order
for(int i=length-1;i>=0;--i){
if(i>=charArray.size()){
charArrayFinal.add((char) 48); // sends 0 to fix the length of the output List
} else {
charArrayFinal.add(charArray.get(i));
}
}
Example:例子:
(278197) 36 =5YNP (278197) 36 =5YNP
Maybe I'm late to the party, but this is the solution I was using for getting Calc/Excel cell names by their index:也许我迟到了,但这是我用来通过索引获取 Calc/Excel 单元格名称的解决方案:
public static void main(final String[] args) {
final String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println(toCustomBase(0, base));
System.out.println(toCustomBase(2, base));
System.out.println(toCustomBase(25, base));
System.out.println(toCustomBase(26, base));
System.out.println(toCustomBase(51, base));
System.out.println(toCustomBase(52, base));
System.out.println(toCustomBase(520, base));
}
public static String toCustomBase(final int num, final String base) {
final int baseSize = base.length();
if(num < baseSize) {
return String.valueOf(base.charAt(num));
}
else {
return toCustomBase(num / baseSize - 1, base) + base.charAt(num % baseSize);
}
}
Results:结果:
A
C
Z
AA
AZ
BA
TA
Basically the solution accepts any custom radix.基本上该解决方案接受任何自定义基数。 The idea was commandeered from here .这个想法是从这里征用的。
Not sure if the above answers did help but noting 'decimal' and 'to base36' I assume you want to convert a numeric value to base36.不确定上面的答案是否有帮助,但注意“十进制”和“到 base36”我假设您想将数值转换为 base36。 And as long as the Long
value of the raw figure is within ( 0 - Long.MAX_VALUE
):只要原始图形的Long
值在 ( 0 - Long.MAX_VALUE
) 内:
String someNumericString = "9223372036854";
Long l = Long.valueOf(someNumericString);
String bases36 = Long.toString(l, 36);
System.out.println("base36 value: "+bases36);
output: 39p5pkj5i
输出: 39p5pkj5i
Here is a method to convert base 10 to any given base.这是一种将基数 10 转换为任何给定基数的方法。
public char[] base10Converter(int number, int finalBase) {
int quo;
int rem;
char[] res = new char[1];
do {
rem = number % finalBase;
quo = number / finalBase;
res = Arrays.copyOf(res, res.length + 1);
if (rem < 10) {
//Converting ints using ASCII values
rem += 48;
res[res.length - 1] = (char) rem;
} else {
//Convert int > 9 to A, B, C..
rem += 55;
res[res.length - 1] = (char) rem;
}
number /= finalBase;
} while (quo != 0);
//Reverse array
char[] temp = new char[res.length];
for (int i = res.length - 1, j = 0; i > 0; i--) {
temp[j++] = res[i];
}
return temp;
}
This can be helpful to you.The operation being performed on the 4 digit alphanumeric String and decimal number below 1679615. You can Modify code accordingly.这对您有帮助。对1679615以下的4位字母数字字符串和十进制数字执行的操作。您可以相应地修改代码。
char[] alpaNum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
String currentSeries = "";
int num = 481261;
String result = "";
String baseConversionStr = "";
boolean flag = true;
do
{
baseConversionStr = Integer.toString(num % 36) + baseConversionStr;
String position = "";
if(flag)
{
flag = false;
position = baseConversionStr;
}
else
{
position = Integer.toString(num % 36);
}
result += alpaNum[new Integer(position)];
num = num/36;
}
while (num > 0);
StringBuffer number = new StringBuffer(result).reverse();
String finalString = "";
if(number.length()==1)
{
finalString = "000"+articleNo;
}
else if(number.length()==2)
{
finalString = "00"+articleNo;
}
else if(number.length()==3)
{
finalString = "0"+articleNo;
}
currentSeries = finalString;
I got this code from this website in JavaScript, and this is my version in java:我从这个网站的 JavaScript 中得到了这段代码,这是我的 Java 版本:
public static String customBase (int N, String base) {
int radix = base.length();
String returns = "";
int Q = (int) Math.floor(Math.abs(N));
int R = 0;
while (Q != 0) {
R = Q % radix;
returns = base.charAt(R) + returns;
Q /= radix;
}
if(N == 0) {
return String.valueOf(base.toCharArray()[0]);
}
return N < 0 ? "-" + returns : returns;
}
This supports negative numbers and custom bases.这支持负数和自定义基数。
Decimal Addon:十进制插件:
public static String customBase (double N, String base) {
String num = (String.valueOf(N));
String[] split = num.split("\\.");
if(split[0] == "" || split[1] == "") {
return "";
}
return customBase(Integer.parseInt(split[0]), base)+ "." + customBase(Integer.parseInt(split[1]), base);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.