[英]How to convert String to BigInteger representation and back in Java?
假設我有一個String
,我們稱之為foo
。 此String
可以包含任何值,如字母,數字,特殊字符, UTF-8
特殊字符,如á等。 例如,這可能是一個真正的價值:
"Érdekes szöveget írtam a tegnap, 84 ember olvasta."
我想有以下兩種方法:
public BigInteger toBigInteger(String foo)
{
//Returns a BigInteger value that can be associated with foo
}
public String fromBigInteger(BigInteger bar)
{
//Returns a String value that can be associated with bar
}
然后:
String foo = "Érdekes szöveget írtam a tegnap, 84 ember olvasta.";
System.out.println(fromBigInteger(toBigInteger(foo)));
//Output should be: "Érdekes szöveget írtam a tegnap, 84 ember olvasta."
我怎樣才能做到這一點? 謝謝
以下代碼將按預期執行:
public BigInteger toBigInteger(String foo)
{
return new BigInteger(foo.getBytes());
}
public String fromBigInteger(BigInteger bar)
{
return new String(bar.toByteArray());
}
但是我不明白為什么你需要這樣做,我會對你的解釋感興趣。
忽略“你為什么要這么做?”
String foo = "some text";
byte[] fooBytes = foo.getBytes();
BigInteger bi = new BigInteger(fooBytes);
接着
foo = new String(bi.toByteArray());
從評論編輯:這是使用默認的字符集。 如果源String
未通過默認編碼,則需要為getBytes()
和String
的構造函數指定適當的Charset
。 如果你正在使用第一個字節為零的字符集,那么這將失敗。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.