문제

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,

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top