Home > Back-end >  Why am I getting a number format exception when the data type accepts the values im parsing?
Why am I getting a number format exception when the data type accepts the values im parsing?

Time:12-27

I do not want the answer, I would just like guidance and for someone to point to why my code is not performing as expected

My task is to flip an integer into binary, reformat the binary to a 32 bit number and then return the unsigned integer. So far my code successfully makes the conversions and flips the bits however I am getting a NumberFormatException when I attempt to parse the string value into a long that ill convert to an unsigned integer.

What is the issue with my code? What have I got misconstrued here? I know there are loads of solutions to this problem online but I prefer working things out my own way?

Could I please get some guidance? Thank you

public class flippingBits {
    public static void main(String[] args) {

        //change the number to bits
        long bits = Long.parseLong(Long.toBinaryString(9));
        String tempBits = String.valueOf(bits);

        //reformat so that you get 32 bits
        tempBits = String.format("%"   (32)   "s", tempBits).replace(" ", "0");

        //flip the bits
        tempBits = tempBits.replace("1", "5");
        tempBits = tempBits.replace("0", "1");
        tempBits = tempBits.replace("5", "0");

        //Pass this to a long data type so that you can then eventually convert the new bits
        // to an unsigned integer

        long backToNum = Long.parseLong(tempBits);
    }
}

CodePudding user response:

You're directly parsing the bits into a long value instead of converting the bits into an equivalent value.

You need to use the following method (enter image description here

  • Related