d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > How To Convert Decimal To Binary In Java
Add Reply New Topic New Poll
Member
Posts: 5
Joined: Jul 11 2022
Gold: 0.00
Jul 26 2022 05:58am
Most inputs to the program turn out great yet when I utilize huge numbers for example 20 the value is incorrect.

Code
int n = Comp122.getInt("What number would you like to make a factorial?");
int factorial = 1;
for (int i = 1 ; i<=n ; i++) {
factorial*=i;
System.out.println(factorial);
}


From Scaler (https://www.scaler.com/topics/binary-to-decimal-in-java/) and Wiki (https://en.wikipedia.org/wiki/Binary-coded_decimal) I got the resolution, but still unsure about it. Need your valuable insights on it. Is there a way I could change over the decimal numbers and result them as binary?
Member
Posts: 12,703
Joined: May 17 2013
Gold: 12,935.00
Jul 26 2022 06:49am
the title talks about binary, but you are creating n! (factorial)

..what?
Member
Posts: 51
Joined: Oct 31 2021
Gold: 0.00
Jul 31 2022 01:36am
Your answer can not fit in a "int" data type. Java's default int is 32bit signed, which gives a range of -2147483648 to 2147483647.
20! = 2432902008176640000.

You need a datatype capable of holding such a large number. Checkout BigInteger.
Member
Posts: 17,000
Joined: Oct 24 2010
Gold: 0.00
Warn: 30%
Aug 1 2022 02:30pm
just use a built in method like Integer.toBinaryString()

example:
Code
System.out.println("Decimal 12 is " + Integer.toBinaryString(12) + " in binary.");


output:
Code
Decimal 12 is 1100 in binary.


This post was edited by OnChair on Aug 1 2022 02:31pm
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll