在Java中将字符串编码/解码为大整数

我正在研究一个实现,我应该将长哈希转换为来回(函数应该是可逆的),但我没有弄清楚如何让它在Java中与这些类一起工作。StringBigInteger


我的第一个想法是做如下事情:


given s:String

for every character in the input string:

    convert char to decimal ASCII representation (i.e. 'a' -> '97')

    append result to s

build a BigDecimal with the resulting s

但问题是(正如许多用户所评论的那样)转换的长度,因为ASCII字符从0到255。它可以从 更改为 ,但是在解码中再次存在问题,删除每个字符的标题零(顺便说一句,算法效率较低)'a' -> '97''a' -> '097'


因此,总而言之,这里提出的算法不是最好的主意,所以我对其他一些解决方案持开放态度。此外,如果 和/或 中有任何库或内置方法,它也很有帮助。签名是StringBigInteger


public class EncodeUtil {

    public BigInteger encode(String s) {...}

    public String decode(BigInteger bi) {...}

}

条件是输出decode(encode("som3_We1rd/5+ring"))"som3_We1rd/5+ring"


我认为值得一提的是,用于解码的接收字符串是哈希值,例如lQ5jkXWRkrbPlPlsRDUPcY6bwOD8Sm/tvJAVhYlLS3WwE5rGXv/rFRzyhn4XpUovwkLj2C3zS1JPTQ1FLPtxNXc2QLxfRcH1ZRi0RKJu1lK8TUCb6wm3cDw3VRXd21WRsnYKg6q9ytR+iFQykz6MWVs5UGM5NPsCw5KUBq/g3Bg=


欢迎任何想法/建议。提前感谢您抽出宝贵时间接受采访。


慕桂英4014372
浏览 155回答 1
1回答

呼唤远方

这大约可以满足您的要求 - 但是,特别是当每个“十进制ASCII表示”的位数可变时,您所要求的内容将不起作用。另外,你想要的不是哈希函数:public class Driver {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; String s = "Reversible Hash a String to BigInteger in Java";&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(HashUtil.notReallyHash(s));&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(HashUtil.notReallyUnhash(HashUtil.notReallyHash(s)));&nbsp; &nbsp; }}class HashUtil {&nbsp; &nbsp; private static final byte SENTINEL = (byte) 1;&nbsp; &nbsp; public static BigInteger notReallyHash(String s) {&nbsp; &nbsp; &nbsp; &nbsp; CharBuffer charBuf = CharBuffer.wrap(s.toCharArray());&nbsp; &nbsp; &nbsp; &nbsp; ByteBuffer byteBuf = ByteBuffer.allocate(charBuf.length() * Character.BYTES + 1);&nbsp; &nbsp; &nbsp; &nbsp; byteBuf.put(SENTINEL); // need this in case first byte is 0 - biginteger will drop it&nbsp; &nbsp; &nbsp; &nbsp; byteBuf.asCharBuffer()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.append(charBuf);&nbsp; &nbsp; &nbsp; &nbsp; return new BigInteger(1, byteBuf.array());&nbsp; &nbsp; }&nbsp; &nbsp; public static String notReallyUnhash(BigInteger bi) {&nbsp; &nbsp; &nbsp; &nbsp; ByteBuffer byteBuf = ByteBuffer.wrap(bi.toByteArray());&nbsp; &nbsp; &nbsp; &nbsp; byteBuf.get(); // SENTINEL&nbsp; &nbsp; &nbsp; &nbsp; CharBuffer charBuf = byteBuf.asCharBuffer();&nbsp; &nbsp; &nbsp; &nbsp; StringBuilder sb = new StringBuilder();&nbsp; &nbsp; &nbsp; &nbsp; int count = charBuf.length();&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < count; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sb.append(charBuf.get());&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return sb.toString();&nbsp; &nbsp; }}收益 率:361926078700757358567593716803587125664654843989863967556908753816306719264539871333731967310574715835858778584708939316915516582061621172700488541380894773554695375367299711405739159440282736685351257712598020862887985249Reversible Hash a String to BigInteger in Java
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java