Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

Decimal to Binary In Java

Status
Not open for further replies.

HarshJain

Newbie
Newbie level 3
Joined
Jul 11, 2022
Messages
3
Helped
0
Reputation
0
Reaction score
0
Trophy points
1
Location
India
Activity points
35
So I have code that will convert a decimal number to binary. I use a recursive algorithm for it, however, I cannot seem to get it to do what I want. Here is the code:

Code:
import java.util.*;

public class binaryAddition {

    public static int toBinary(int a){


        int bin = 0;
        int remainder = 0;
        if(a >= 1){
            toBinary(a/2);
            bin = (a%2);
        }

        return bin;


    }

    public static void main(String[] args){

        System.out.println(toBinary(3));
        System.out.print(toBinary(3));
    }
}

So I want to return the binary solution so that I can save it as a variable in my main method. However, my current output would only give me that last digit of the binary number. I utilized the number 3 similarly as an experiment and I get 1 as a result for both print and println techniques. Why would that be, and how might I fix it?

Before trying this code I have done several research on the web and read a couple of articles on binary to decimal in java to understand the concept in a better way, my source of Information is Wiki, scaler, and GFG.

Much obliged!
 

Hi,

to be honest, I don´t understand what your code tries to do.

binary ... decimal ... hex ... ASCII ... are just phrases how a value is represented.
Usually you don´t need a conversion at all.

example: 0b01000001 = 65 = 0x41 = "A"
So it does not matter whether you store 0b01000001 or 65 to a memory ... the content will be the same. No need for a conversion.

Maybe you could give an example what´s your input value and output value.

Klaus
 

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top