Re: Interesting Integer.parseInt() problem



Knute Johnson wrote:
I'm working on a project where I'm being given a string of 0s and 1s and need to mask them against another string of the same. I thought I would convert my string with Integer.parseInt("111",2) but I ran into a problem. You can't parse out 32 bits to an int if the MSB is 1. It throws a NumberFormatException. You can't parse -2147483648 in either radix 2, 8 or 16. My data is of course LSB first so 1 would be 100000000000000000000000000000000 and I can't parse it. Anyway, I thought it was interesting and wondered if anybody knows why this is so?

Presumably because you can't represent 1<<31 in a 32-bit signed number. Nor can int represent -2147483648 (base 16). -2147483648 contains digits not in base 2 or 8.


Although Integer.toBinaryString and friends create representations of the number as if it is unsigned, Integer.parseInt treats the value is normally.

If your data is LSB first, you'll need to reverse it, anyway. StringBuilder will do that nicely for you.

Tom Hawtin
--
Unemployed English Java programmer
http://jroller.com/page/tackline/
.



Relevant Pages

  • Re: Help With PyParsing of output from win32pdhutil.ShowAllProcesses()
    ... None to a string). ... Still have an urge to parse with pyparsing? ... pyparsing Dict class. ... keys from the parsed data, so it looks like you are already thinking ...
    (comp.lang.python)
  • Re: Pyparsing help
    ... our grammar isn't parsing the METAL2 entry at all. ... input string". ... successful parse, then restored half of the entries I removed, until I ... Layer PRBOUNDARY ...
    (comp.lang.python)
  • Re: Nasty code...but please critique it anyway :-)
    ... You only need <string>, move all the other #includes to the C++ files. ... compilation times. ... You may want to use a std::stringstream to parse the integer, ... You may want to flush the output stream after printing menutext, ...
    (alt.comp.lang.learn.c-cpp)
  • Re: Nasty code...but please critique it anyway :-)
    ... You only need <string>, move all the other #includes to the C++ files. ... compilation times. ... You may want to use a std::stringstream to parse the integer, ... You may want to flush the output stream after printing menutext, ...
    (comp.lang.cpp)
  • Re: Parsing a string
    ... to parse names. ... > I didn't have the errorhandler in testing, ... > records and the function encounters an error, ... strPrefix As String ...
    (microsoft.public.access.queries)