This week's giveaway is in the EJB and other Java EE Technologies forum. We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line! See this thread for details.
Given the following Strings that represent binary numbers in two's complement:
Does a method exist in Java that will convert those strings to their decimal representation?
I have created a method that does the conversion correctly, but it seems like I am re-inventing the wheel since I'm sure it is common to do a two's complement binary number to decimal conversion. It involves looking at the first character for the sign, and if it is '1' (negative), flip each bit, call Integer.parseInt(bitFlippedValue, 2), add 1 and multiply by -1, else if the first character is '0', simply call Integer.parseInt(value, 2).
I'd try looking at the java API, and the Integer class, to see if there is some method that would parse a string
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Joined: Aug 18, 2010
fred rosenberger wrote:I'd try looking at the java API, and the Integer class, to see if there is some method that would parse a string
That's the first place I looked. I couldn't find a method that would convert a 32 bit two's complement binary number as a String into an integer value. Integer.parseInt works for only positive numbers.