• Java Binary to Decimal Conversion

    Home » Forums » Developers, developers, developers » DevOps Lounge » Java Binary to Decimal Conversion

    Tags:

    Author
    Topic
    #2504053

    I’m almost finished writing code that allows a user to enter a decimal number into binary, have the binary value reversed, and then convert it back to decimal.

    Except for the Binary to Decimal phase, I solved everything. No matter what I type, it continues returning the same number to me. I’m not sure why I attempted to grasp this blog but it didn’t assist me. Simply put, why is the last section of my code incorrect? I’m having difficulties determining the length of the array/string and then multiplying it by 2n, etc.

    package reversedBinary;
    import java.util.Scanner;
    
    public class ReversedBinary {
    
    
    public static void main(String[] args) {
        int number; 
    
        Scanner in = new Scanner(System.in);
    
        System.out.println("Enter a positive integer");
        number=in.nextInt();
    
        if (number <0)
            System.out.println("Error: Not a positive integer");
        else { 
    
            System.out.print("Convert to binary is:");
            System.out.print(binaryform(number));
    }
    
    }
    
    private static Object binaryform(int number) {
        int remainder;
    
        if (number <=1) {
            System.out.print(number);
    
        }
    
        remainder= number %2; 
        binaryform(number >>1);
        System.out.print(remainder);
    
        { 
        return null;
    } } }
    • This topic was modified 2 years, 5 months ago by Mobo01.
    • This topic was modified 2 years, 5 months ago by Mobo01.
    Viewing 2 reply threads
    Author
    Replies
    • #2504117

      I know nothing about Java but I do know that conversion is built-in to PowerShell. Do you really need to do in Java?

      Foe example:

      ps_convert_binary_to_decimal

      If this is of any interest then have a look at Use PowerShell to Easily Convert Decimal to Binary and Back.

      Hope this helps…

      1 user thanked author for this post.
    • #2504135

      It isn’t working because your binaryform subroutine isn’t actually doing any of the math required to actually convert the decimal number into a binary value!

        It needs to keep dividing the decimal number by 2 and record the result of the division as a “string value” of either 1 or 0 (0 = no remainder, 1 = remainder) until the results of the final division is either 0 or 1.

        The recorded results of each division must be added to a “string value” that’s what gets displayed as the binary value when the routine is done.

      With your problem explained, it’d be “much simpler” to use Java’s Integer.toBinaryString command.

        i.e.  replace System.out.print(binaryform(number)); with System.out.print(Integer.toBinaryString(number));

      And remove the whole binaryform subroutine.

      2 users thanked author for this post.
    • #2577518

      It seems you are trying to implement a Java program that converts a decimal number to its binary representation, reverses the binary value, and then converts it back to decimal. However, you are encountering issues with the binary-to-decimal conversion part of the code. Let’s address the problem and provide the solution:

      Firstly, you need to reverse the binary string and then convert it back to decimal. The issue in your current code is that you are not storing the binary digits in a proper data structure to reverse them correctly.

      Here’s the corrected version of your code:

      `java
      import java.util.Scanner;

      public class ReversedBinary {

      public static void main(String[] args) {
      int number;

      Scanner in = new Scanner(System.in);

      System.out.println(“Enter a positive integer”);
      number = in.nextInt();

      if (number < 0)
      System.out.println(“Error: Not a positive integer”);
      else {
      System.out.print(“Convert to binary is:”);
      String binary = binaryform(number);
      System.out.print(binary);
      int reversedDecimal = binaryToDecimal(reverseString(binary));
      System.out.println(“\nReversed decimal value is: ” + reversedDecimal);
      }
      }

      private static String binaryform(int number) {
      int remainder;
      StringBuilder binaryString = new StringBuilder();

      if (number <= 1) {
      binaryString.append(number);
      }

      remainder = number % 2;
      binaryString.append(binaryform(number >> 1));
      binaryString.append(remainder);

      return binaryString.toString();
      }

      private static String reverseString(String str) {
      StringBuilder reversed = new StringBuilder(str);
      return reversed.reverse().toString();
      }

      private static int binaryToDecimal(String binary) {
      int decimal = 0;
      int len = binary.length();

      for (int i = 0; i < len; i++) {
      if (binary.charAt(i) == ‘1’) {
      decimal += Math.pow(2, len – 1 – i);
      }
      }

      return decimal;
      }
      }
      <code></code>`

      In this corrected version, we have made the following changes:

      1. Added a method reverseString to reverse the binary string.
      2. Added a method binaryToDecimal to convert the reversed binary string back to decimal.
      3. Modified the binaryform method to return a binary string as a String instead of Object.
      4. Used StringBuilder to efficiently construct the binary string.

      Now, your program should properly convert the decimal number to binary, reverse the binary representation, and convert it back to decimal as desired. To see the results, you can try running the program with different input values.

      Moderator note: Removed link that returned 404 error.

    Viewing 2 reply threads
    Reply To: Java Binary to Decimal Conversion

    You can use BBCodes to format your content.
    Your account can't use all available BBCodes, they will be stripped before saving.

    Your information: