Trouble converting decimal value to binary - java

I'm making a program that converts decimal values to binary and vice versa. I've figured out how to convert binary to decimal, however I am having trouble with decimal to binary. I've seen many sources with code on how to do it but most of them involve using an array. I can't use an array because this program has a GUI and JLabel can't print the array. I've found a code that works with certain numbers, but doesn't with others. Here's the code:
public void convertBinary (int decimal)
{
String binary = "";
int remainder;
while (decimal != 0)
{
remainder = decimal % 2;
decimal /= 2;
binary += remainder;
}
lblDecBinAns.setText(String.valueOf(binary));
}
The given number is inputted by the user ("decimal") which is taken when they press the button. I don't know if there's an adjustment that can be made to this code for it to work properly. Perhaps there's an entirely different algorithm that would work for this or maybe a way to print an array with JLabel. I've been stumped on this for a while so any help is appreciated. Thanks.
P.S.
I'm aware of the .toBinary function, but I must create my own method for this one.

You got it done, the only thing you are missing is to REVERSE the binary string
int decimal=10;
String binary = "";
int remainder;
while (decimal != 0)
{
remainder = decimal % 2;
decimal /= 2;
binary += remainder;
}
System.out.println(new StringBuilder(binary).reverse().toString());
yelds
1010 as result

You need to add remainder as binary = remainder + binary or reverse the string. And no need to use String.valueOf since it's already a string. And also consider the case when decimal is zero you need to send 0
public String convertBinary(int decimal) {
String binary = "";
int remainder;
if(decimal == 0) {
return "0";
}
while (decimal != 0) {
remainder = decimal % 2;
decimal /= 2;
binary = remainder + binary;
}
return binary;
}

For a different twist, you can also do it like this.
Initialize the result to an empty string.
Using the AND & operator, mask off the low order bit. You could also use the remainder % operator here too.
Convert the bit, 1 or 0, to a string and prepend it to the result string.
Right shift the number (decimal) by 1 bit so the next bit can be checked.
while(!(decimal>>>1) == 0)
continue the while loop until decimal == 0 (i.e. all 1 bits have been shifted out of the number).
public static String toBinary(int decimal) {
// intialize the string
String binary = Integer.toString(decimal&1);
while ((decimal>>>=1) != 0) {
binary = Integer.toString(decimal&1)+ binary;
// or binary = Integer.toString(decimal % 2) + binary;
}
return binary;
}

Have you tried this?
String test = Integer.toString(n, 2); //n is the number to convert and 2 the base (binary). In case you want an octal number, for example, just change the base to 8.
But using this will cause problem in case you want to reconvert that String into a number just like this:
int number = Integer.parseInt(test); //This will cause NumberFormatException.
To avoid the error, each char of test must be converted to a char
char digit = test.charAt(i);
Finally, convert each char to a individual String again
String converted = String.valueof(digit);
And now you can convert the new String into an int

Related

Java Fraction Base Conversion [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I want to convert a source base number to a destination base number, but I have a problem with fractions. When I trying to convert 10.234 (base10) to base 7 = 13.14315 it works perfectly, or aaaaa.0 (base16) to base 24 = 22df2 it also works.
But when I try to convert aaaaa.cdefb0 (base16) to base 24 = 22df2.j78da it doesn't work. I can't calculate fraction part and I get 22df2 as the answer
my code for base conversion :
private static String baseConversion(String number,
int sBase, int dBase) {
return Long.toString(
Long.parseLong(number, sBase),
dBase);
}
my code for fraction conversion :
private static String fractionConversion(double fraction, int dBase) {
StringBuilder output = new StringBuilder(".");
for (int i = 0; i < PRECISION; i++) {
fraction *= dBase;
output.append(Long.parseLong(Integer.toString((int) fraction)));
fraction -= Long.parseLong(Integer.toString((int) fraction));
}
return output.toString();
}
In your code below you should be appending a symbol for the base, not a number. Use the number to index into an array of symbols for the base.
And I recommend using integers for your remainder and product computations as you will eventually lose precision using floating point values.
for (int i = 0; i < PRECISION; i++) {
fraction *= dBase;
// what are you appending here? It should be a symbol
output.append(Long.parseLong(Integer.toString((int) fraction)));
fraction -= Long.parseLong(Integer.toString((int) fraction));
}
Here's a more complete example.
static String symbols = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// assumes a string in the form of .293093
// number of places
// destination radix.
public static String expand(String decimalFraction, int places, int dr) {
decimalFraction = decimalFraction.substring(1); // ignore decimal point
int numerator = Integer.parseInt(decimalFraction);
int denominator = (int) Math.pow(10, decimalFraction.length());
StringBuilder sb = new StringBuilder(".");
for (int i = 0; i < places; i++) {
numerator *= dr;
sb.append(symbols.charAt((int) (numerator / denominator)));
numerator %= denominator;
if (numerator == 0) {
break;
}
}
return sb.toString();
}
I earnestly cannot recommend doing this, but I'll answer the question anyhow.
I would simply split the two numbers and treat them separately. First and foremost, how fractions work outside of Base 10 is not a 1-for-1 conversion of the trailing number. .25 in base 10 is not .11001 in binary, it's .01.
Every decimal place in your number represents a new magnitude; in base 10 it's values of 10^-1, 10^-2, and so on. When you change bases, you still change magnitudes but at different rates: 2^-1, etc.
.25 is thus analogous to 2/10 + 5/100 in base 10, and 0/2 + 1/4 in base 2. This leads to a new problem, where if the divisor of a fraction isn't a power of your new base, you usually get an irrational number. 1/20 is .05 in decimal, but in base 2 it's:
0.00 0011 0011 0011 //endless
This more or less leads to why fractional numbers are not normally converted between bases. You will lose precision and it's not a small task. But essentially the algorithmic conversation is the same as for whole numbers, but instead of dividing the number by the base and using the remainder as your output, you multiply by the base and use the division as your output.
int decimalPart = ...; //for example, "375", represents .375 or 3/8
int magnitude = Math.pow(10, ("" + decimalPart).length());
int newBase = 2; //again, bases that don't divide into each other will be messy, like 7 and 10
StringBuilder out = new StringBuilder();
//The below should be limited for precision, or you may loop forever
while (decimalPart > 0) {
decimalPart *= newBase;
out.append(decimalPart / magnitude);
decimalPart %= magnitude.
}
String result = sb.toString();
//"375" -> "011"

why does modulus by a large number seem to give a wrong answer in Java

I am trying to find trailing numbers of zeros in a number, here is my code:
public class TrailingZeroes {
public static void bruteForce(int num){ //25
double fact = num; //25
int numOfZeroes = 0;
for(int i= num - 1; i > 1; i--){
fact = fact * (i);
}
System.out.printf("Fact: %.0f\n",fact); //15511210043330984000000000
while(fact % 10 == 0){
fact = fact / 10;
double factRem = fact % 10;
System.out.printf("Fact/10: %.0f\n",fact); //1551121004333098400000000
System.out.printf("FactRem: %.0f\n",factRem); // 2?
numOfZeroes++;
}
System.out.println("Nnumber of zeroes "+ numOfZeroes); //1
}
}
As you can see the fact%10
You use floating point data type illegally.
The float and double primitive types in Java are floating point numbers, where the number is stored as a binary representation of a fraction and a exponent.
More specifically, a double-precision floating point value such as the double type is a 64-bit value, where:
1 bit denotes the sign (positive or negative).
11 bits for the exponent.
52 bits for the significant digits (the fractional part as a binary).
These parts are combined to produce a double representation of a value.
For a detailed description of how floating point values are handled in Java, see the Section 4.2.3: Floating-Point Types, Formats, and Values of the Java Language Specification.
The byte, char, int, long types are [fixed-point][6] numbers, which are exact representions of numbers. Unlike fixed point numbers, floating point numbers will some times (safe to assume "most of the time") not be able to return an exact representation of a number. This is the reason why you end up with 11.399999999999 as the result of 5.6 + 5.8.
When requiring a value that is exact, such as 1.5 or 150.1005, you'll want to use one of the fixed-point types, which will be able to represent the number exactly.
As has been mentioned several times already, Java has a BigDecimal class which will handle very large numbers and very small numbers.
public static void bruteForce(int num) { //25
double fact = num;
// precision was lost on high i
for (int i = num - 1; i > 1; i--)
fact *= i;
String str = String.format("%.0f", fact); //15511210043330984000000000
System.out.println(str);
int i = str.length() - 1;
int numOfZeroes = 0;
while (str.charAt(i--) == '0')
numOfZeroes++;
System.out.println("Number of zeroes " + numOfZeroes); //9
}

Converstion from int to binary

Is there a way to convert an int to binary number without using Integer.toBinaryString method?
I tried to figure out the algorithm for the conversion but haven't had any luck with it.
My task is this: (https://open.kattis.com/problems/reversebinary)
Insert an Int with help of Scanner.
Convert the Int to binary.
Reverse the binary.
Print out the new Int.
For example, the number 11 is 1011 in binary.
Now reverse the binary number 1011 and you get 1101 (which is the number 13)
and print out 13.
This is what I got, but still, I used the Integer.toBinaryString method and I get NumberFormatException.
int reverse = 0;
int number, binary;
Scanner scn = new Scanner(System.in);
number = scn.nextInt();
String b = Integer.toString(number, 2);
binary = Integer.parseInt(b);
while (binary != 0) {
reverse = reverse * 10 + binary % 10;
binary = binary / 10;
}
int newNumber = Integer.parseInt(String.valueOf(reverse), 2);
System.out.println(newNumber);
}
}
First of all, you should use the correct terms. You are not converting an int to a binary. The int type (as well as all numeric types) are already stored in a binary format. When you convert an int to a String, or a String to an int, you choose the radix that the String representation uses (such as decimal, binary, octal, hexadecimal, etc..). This determines the digits that appear in the String representation. Now, based on your example, what you wish to do is generate a number whose binary representation is the reverse of the input number. In other words, you want to reverse the bits of the input number.
Your current loop :
while (binary != 0) {
reverse = reverse * 10 + binary % 10;
binary = binary / 10;
}
calculates the decimal (radix 10) digits of binary and creates an integer whose value is the value of those digits when they are arranged in reversed order.
If you want the reverse of the binary representation of the input number, you should multiply and divide by 2 in order to obtain the binary digits (aka bits) of the input number and reverse them :
while (number != 0) {
System.out.print (number % 2); // prints a binary digit (i.e. 0 or 1)
reverse = reverse * 2 + number % 2;
number = number / 2;
}
System.out.println();
System.out.println(reverse); // prints the decimal representation of the reversed number
If number is 11, reverse will be 13, since the reverse of 1011 is 1101. This code will print both the binary representation of the reversed number (1101) and the decimal representation (13).
Instead of reversing the binary as a number, reverse it while it is still a String, new StringBuilder(b).reverse().toString(). Then convert it back to an int from base 2, and you're done.
So the entire code would be:
final Scanner scn = new Scanner(System.in);
final int number = scn.nextInt();
String b = Integer.toString(number, 2);
b = new StringBuilder(b).reverse().toString();
System.out.println(Integer.parseInt(b.toString(), 2));
Maybee the smartest solution for this problem is bit shifting. I wrote an example with a little explanation.
int number, reverse = 0;
Scanner scn = new Scanner(System.in);
number = scn.nextInt();
while (number > 0)
{
// shift all bits to the left
reverse = reverse << 1;
// extract the last bit of the number
int bit = number & 1;
// add the last bit to the reverse version
reverse |= bit;
// shift alle bits to the right
number = number >> 1;
}
System.out.println(reverse);
Integer.toBinaryString - Returns a string representation of the integer argument as an unsigned integer in base 2.
String toString(int i, int radix) -
Returns a string representation of the first argument in the radix specified by the second argument
public static void main(String[] args) {
int reverse = 0;
int number, binary;
Scanner scn = new Scanner(System.in);
number = scn.nextInt();
String b = Integer.toBinaryString(number);
binary = Integer.parseInt(b);
while (binary != 0) {
reverse = reverse * 10 + binary % 10;
binary = binary / 10;
}
int newNumber = Integer.parseInt(String.valueOf(reverse), 2);
System.out.println(newNumber);
}
Infact whatever you use cannot give an error. The above code perfectly compiles without an error.
Providing 11, gives 13 perfectly.

How to convert decimal to a higher base and vice versa

As a programming assignment for my java CSC class I have written the following code to convert a number and its base to a decimal number and then to a desired number and base.
public static int baseten(int number,int basein){
int power = 0;
int baseten = 0;
while (number > 0) {
int finalDigit = number % 10;
int product = finalDigit*(int)Math.pow(basein, power);
baseten += product;
number = number / 10;
power++;
}
return(baseten);
}
public static String convert (int decimal, int baseout){
String result = "";
while (decimal > 0){
//if baseout
int remainder = decimal % baseout;
decimal = decimal / baseout;
result = remainder + result;
}
return(result);
}
The question is how to convert a number to a base higher than ten within this code? I assume maybe a char[], but I'm not very good with arrays right now and can't imagine what that might look like. I don't think I can use toString's or parseInt's. Any help would be appreciated. Thanks in advance.
You are almost there. What you could do is insert an if/else statement to determine whether the remainder is greater or equal to ten or not and act accordingly. If it isn't, do what you're doing right now. If it is, then you need to add a char to your string. This char must be (remainder-10) + 65, since 65 is capital A on the ascii table and you need to know how many digits above ten remainder is and add that to A. This could be simplified to simply adding 55, but that is less readable in my opinion. Then, just add that char to the string instead of adding the int.

Java get fraction method

I am trying to make a method that returns the fractional value of a decimal number.
//these are included in a class called 'equazioni'
private static long getMCD(long a, long b) {
if (b == 0)
{ return a; }
else
{ getMCD(b, a % b); }
}
public String getFraction(double a) {
String s = String.valueOf(a);
int decimali = s.length() - 1 - s.indexOf('.');
int den = 1;
for(int i = 0; i < decimali; i++){
a *= 10;
den *= 10;
}
int num = (int) Math.round(a);
long mcd = getMCD(num,den);
return String.valueOf(num/mcd) + "/" + String.valueOf(den/mcd);
}
These 2 methods works perfectly with most of values. For example with a 8.65 it returns a 173/20, or 78.24 it returns a 1956/25. It's called in this way:
equazioni eq = new equazioni(a,b,c);
jTextField4.setText("8.65= " + eq.getFraction(8.65));
I am having troubles with fractions like 2/3, 5/18, 6/45... because the denominator is divisible by 3 and so the fraction is a periodic number. How could I represent it?
My problem is also "How could I recognize that it's a periodic number?". I thought that I could something like this
int test = den % 3;
If the denominator is divisible by 3, then I have to generate a fraction in a particular way. Any suggestion?
If I correctly understood your question, I am afraid it does not have a complete solution. Since a float is stored with a finite number of bits, not all fractions can be represented, especially the ones that are not decimal numbers like 2/3. Even for decimal numbers, not all of them can be represented.
In other words, your method will never be called by the float representation of 2/3 as an input, since this representation does not exist. You might be called with 0.66666666 (with whatever the limit of digits would be in Java), but that is not 2/3...
See this link for more details about floating point representation in Java: http://introcs.cs.princeton.edu/java/91float/

Categories

Resources