Question

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?

Was it helpful?

Solution

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,

OTHER TIPS

If you're sending it as part of an XML file, you have to use the correct datatype definition. XML schema supports a lot of different built-intypes to describe your types accurately.

So <value>10</value> might currently be describing an integer, which is defined as base 10. You could quite easily describe a new simple type which expresses digits as base 2.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top