asteri
asteri

Reputation: 11572

Is there a way to preserve or modify in-code radix information?

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?

Upvotes: 1

Views: 84

Answers (2)

David Grant
David Grant

Reputation: 14223

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.

Upvotes: 2

Anders R. Bystrup
Anders R. Bystrup

Reputation: 16060

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,

Upvotes: 2

Related Questions