Let's say I have the following code:
int two = 2;
String twoInBinary = Integer.toString(two, 2);
The twoInBinary
String will now hold the value 10
. But it seems like the radix information is completely lost in this transformation. So, if I send twoInBinary
as part of an XML file over a network and want to deserialize it into its integer format, like this...
int deserializedTwo = Integer.parseInt(twoInBinary);
... then deserializedTwo
will equal 10
rather than 2
(in decimal).
I know there is the Integer.parseInt(String s, int radix)
, but in a complex system using many different radixes for many different strings, is it possible to preserve the radix information without having to keep a separate, synchronized log with your values?
Short answer: No, not in standard Java. It is, however, trivial to write a Serializable
class that can transfer the value and radix information over the wire.
class ValueWithRadix implements Serializable
{
int radix;
String value;
}
int deserializedTwo = Integer.parseInt( valueWithRadix.getValue() , valueWithRadix.getRadix() );
Edit: To clarify yet more, the XML on the wire might then look like
<ValueWithRadix>
<value>10</value>
<radix>2</radix>
</ValueWithRadix>
rather than just
<value>10</value>
which of course doesn't preserve radix information.
Cheers,