Integer parsing loop


  • Java Dev

    Today, after a bit of searching, I ran into the following fragment:

    while ( (vallen--) && (basemem[valstart] >= '0') && (basemem[valstart] <= '9') ) {
    numval *= 10;
    numval |= (basemem[valstart++] - '0');
    }


  •  Maybe the author was really sleepy and unable to think.



  • That code is evil in more ways than one.  I like how vallen and valstart both have misleading values after the loop runs.  This thing is probably going to give some very interesting output for "99999999999999999".  Using the or operator for addition or the left shift operator for multiplication are almost always a bad idea.



  • Here, let me FTFY:

    while ( (vallen--) && (basemem[valstart] >= '0') && (basemem[valstart] <= 'f') ) {
    
    numval *= 0x10;
    
    numval |= (basemem[valstart++] - '0');
    

    }

    There, much better now.



  • @PleegWat said:

    Today, after a bit of searching, I ran into the following fragment:

    while ( (vallen--) && (basemem[valstart] >= '0') && (basemem[valstart] <= '9') ) {
    numval *= 10;
    numval |= (basemem[valstart++] - '0');
    }

    Works just fine with my test data.

     

    "0"

    "1"

    "2"

    ...

    "9"

     



  • All your basemem are belong to us.


Log in to reply