How to convert decimal to a higher base and vice versa - java

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.

Related

Here is my question with after changes but still no solution

I have upload this code already but it was having some problems and now I have update my code this program does not provide me exact reverse number when I enter 123 it return me 321 but if I enter 001 or 100 it just return me 1 in both case help me to solve this issue
public class Employee {
void fun(int choice) {
int number = choice;
int remander = 0;
int reverse = 0;
while (number >= 1) {
remander = number % 10;> taking remainder here
reverse = reverse * 10 + remander;
number = number / 10;
}
System.out.println(reverse);
}
public static void main(String args[]) {
Employee ob=new Employee();
int choice;
System.out.println("Enter number you want to return");
Scanner obj=new Scanner(System.in);
choice= obj.nextInt();
ob.fun(choice);
}
}
`
Here's a one-liner you can use to convert int to Stream of String numbers, reverse it and return as a String:
Stream.of(Integer.toString(choice).split("")).reduce((c1,c2)->c2+c1).get();
First point: be careful about adding leading 0s to the number. If the number is an integer literal, the leading 0s will actually cause the integer to be interpreted as octal. In this case, 001 octal does, in fact, equal 1 in decimal too, but only due to luck. If you picked another number, it would not give you the result you're expecting; for example, the following code actually prints 63 (not 77):
public class HelloWorld{
public static void main(String []args){
int x = 0077;
System.out.println(x);
}
}
On the other hand, if you're parsing an integer out of a string or using a scanner, the leading 0s will simply be stripped off. For example, the following prints 77:
System.out.println(Integer.parseInt("0077"));
Unfortunately, in neither case will you get 0077, so the leading 0s won't make any difference when you go to do the reverse operation.
Also, think about what happens for 100:
reverse = reverse * 10 + remander;
Reverse is 0 to start with (and 0 * 10 == 0) and 100 % 10 == 0 because 100 is evenly divisible by 10. Put another way, the statement is equal to:
reverse = 0 * 10 + 0;
which clearly equals 0.
You can't do this using Scanner.nextInt() because there is no way to tell if leading zeroes were included once they are converted to an int. And the octal situation is not relevant since Scanner does not process ints that way. So you use either an all String solution and verify the characters are digits or use a hybrid of both math and String methods. I did the latter. The following:
reads in a String
converts to an int
calculates the number of leading zeroes by using the log10 of the
int and the length of the entered string.
Allocates a StringBuilder to hold the result.
Scanner input = new Scanner(System.in);
String val = input.nextLine();
int numb = Integer.valueOf(val);
int len = val.length();
// exponent of the entered number rounded up to the next int.
// This computes the number of digits in the actual int value.
int exp = (int) Math.log10(numb) + 1;
// now reverse the integer and store in the StringBuilder
StringBuilder sb = new StringBuilder();
while (numb > 0) {
sb.append(numb % 10);
numb /= 10;
}
// and append the leading zeros.
System.out.println(sb + "0".repeat(len - exp));
for input of 00001000
prints 00010000
Note that you are still constrained on input by Integer.MAX_VALUE.

Trouble converting decimal value to binary

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

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
}

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