...
Code Block | ||
---|---|---|
| ||
BigInteger x = new BigInteger ("530500452766"); byte // convert x to a String byte[] byteArray = x.toByteArray(); // convert to byte array String s = new String(byteArray); // s prints as "{,J?z" - // the fourth character is invalid // convert s back to a BigInteger byteArray = s.getBytes(); // convert to bytes x = new BigInteger(byteArray); // now x = 530500435870 |
When run on a platform where the default character encoding is US-ASCII
, the string s
gets the value {{{ÂJÂÂ}}, because some of the characters are unprintable. When converted back to a BigInteger
, x
gets the value 149830058370101340468658109
.
Compliant Solution
This compliant solution first produces a String
representation of the BigInteger
object, and then converts the String
object to a byte array. This process is reversed on input. Because the textual representation in the String
object was generated by the BigInteger
class, it contains valid characters.
Code Block | ||
---|---|---|
| ||
BigInteger x = new BigInteger ("530500452766"); String s = x.toString(); // valid character data try { byte[] byteArray = s.getBytes("UTF8"); String ns = new String(byteArray, "UTF8"); // ns prints as "530500452766" BigInteger x1 = new BigInteger(ns); // construct the original BigInteger } catch (UnsupportedEncodingException ex) { // handle error } |
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="ff4b215ce8648e29-ca8c7e88-47f9461f-85adb7b4-a0deea1a91cbb5a92da26c0f"><ac:plain-text-body><![CDATA[ | [[API 2006 | AA. Bibliography#API 06]] | class [String | http://java.sun.com/javase/6/docs/api/java/lang/String.html] | ]]></ac:plain-text-body></ac:structured-macro> |
...