1 回答
TA贡献1856条经验 获得超11个赞
这大约可以满足您的要求 - 但是,特别是当每个“十进制ASCII表示”的位数可变时,您所要求的内容将不起作用。另外,你想要的不是哈希函数:
public class Driver {
public static void main(String[] args) {
String s = "Reversible Hash a String to BigInteger in Java";
System.out.println(HashUtil.notReallyHash(s));
System.out.println(HashUtil.notReallyUnhash(HashUtil.notReallyHash(s)));
}
}
class HashUtil {
private static final byte SENTINEL = (byte) 1;
public static BigInteger notReallyHash(String s) {
CharBuffer charBuf = CharBuffer.wrap(s.toCharArray());
ByteBuffer byteBuf = ByteBuffer.allocate(charBuf.length() * Character.BYTES + 1);
byteBuf.put(SENTINEL); // need this in case first byte is 0 - biginteger will drop it
byteBuf.asCharBuffer()
.append(charBuf);
return new BigInteger(1, byteBuf.array());
}
public static String notReallyUnhash(BigInteger bi) {
ByteBuffer byteBuf = ByteBuffer.wrap(bi.toByteArray());
byteBuf.get(); // SENTINEL
CharBuffer charBuf = byteBuf.asCharBuffer();
StringBuilder sb = new StringBuilder();
int count = charBuf.length();
for (int i = 0; i < count; i++) {
sb.append(charBuf.get());
}
return sb.toString();
}
}
收益 率:
361926078700757358567593716803587125664654843989863967556908753816306719264539871333731967310574715835858778584708939316915516582061621172700488541380894773554695375367299711405739159440282736685351257712598020862887985249
Reversible Hash a String to BigInteger in Java
添加回答
举报