gpt4 book ai didi

java - 如何将 9 位整数解码为随机 4 位数字

转载 作者:行者123 更新时间:2023-12-01 11:24:38 25 4
gpt4 key购买 nike

如何在java中将7位整数编码为4位字符串?

我有一个base36解码器,它生成6个字符,

例如:230150206 转换为 3T0X1A。

其代码如下:

String f = "230150206";
int d = Integer.parseInt(f.toString());
StringBuffer b36num = new StringBuffer();
do {
b36num.insert(0,(base36(d%36)));
d = d/ 36;
} while (d > 36);
b36num.insert(0,(base36(d)));
System.out.println(b36num.toString());
}

/**
Take a number between 0 and 35 and return the character reprsenting
the number. 0 is 0, 1 is 1, 10 is A, 11 is B... 35 is Z
@param int the number to change to base36
@return Character resprenting number in base36
*/
private static Character base36 (int x) {
if (x == 10)
x = 48;
else if (x < 10)
x = x + 48;
else
x = x + 54;

return new Character((char)x);
}

有人可以分享其他方法来实现这一目标吗?

获得的字符串可以制成子字符串,但我正在寻找其他方法来做到这一点。

最佳答案

这是一个方法,在一个简单的测试程序中。此方法允许任何字符串表示结果的数字。正如最初的打印所示,62 位数字应该足以覆盖所有 7 位十进制数字,且输出不超过 4 个字符,因此我建议在 7 位数字情况下使用十进制数字、小写字母和大写字母。

要用 4 个编码数字覆盖 9 个十进制数字,您至少需要 178 个字符,而仅使用 7 位 ASCII 字符是不可能的。您必须决定使用哪些附加字符作为数字。

public class Test {
public static void main(String[] args) {
String characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println(Math.pow(characters.length(), 4));
testit(230150206, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
testit(230150206, characters);
}

private static void testit(int num, String characters){
System.out.println(num + " "+compact(num, characters));
}

public static String compact(int num, String characters){
StringBuffer compacted = new StringBuffer();
while(num != 0){
compacted.insert(0, characters.charAt(num % characters.length()));
num /= characters.length();
}
return compacted.toString();
}
}

输出:

1.4776336E7
230150206 3T0X1A
230150206 fzGA6

关于java - 如何将 9 位整数解码为随机 4 位数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30929793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com