Over a million developers have joined DZone.

Java low level: Converting between integers and text (part 2)

· Java Zone

Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code! Brought to you in partnership with ZeroTurnaround.

Parsing an integer is relatively simple depending on how many checks you make. This loop does almost no validation. The input can multiple '-' signs and the number can overflow. As soon as it reaches a character is does not accept to stops. It is left to the caller to check if this character was a valid separartor.

ByteBufferTextLongReader.read()
long num = 0;
boolean negative = false;
while (true) {
    byte b = buffer.get();
//  if (b >= '0' && b <= '9')
    if ((b - ('0' + Integer.MIN_VALUE)) <= 9 + Integer.MIN_VALUE)
        num = num * 10 + b - '0';
    else if (b == '-')
        negative = true;
    else
        break;
}
return negative ? -num : num;
Note: The expression (b >= '0' && b <= '9') has been re-written taking advantage of an underflow to turn this into one comparison.

To follow...

Converting floating point numbers to text

 

From http://vanillajava.blogspot.com/2011/07/java-low-level-converting-between_14.html

The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}