This question already has answers here:
How to convert binary string value to decimal
(15 answers)
Closed 5 years ago.
I tried to write a code that convert binary to decimal. But it gives me a huge result. Can you please tell me how to do it. I saw codes using remainder and give correct results but I really wonder what is the fault there in my code, thanks
double number = 0;
for (int i = 0; i < 16; i++) {
double temp = str.charAt(16-1 - i) * Math.pow(2, i);
number = number + temp;
}
Here is where your code went wrong:
str.charAt(16-1 - i) * Math.pow(2, i);
You just multiplied a char by a double. This will evaluate to the ASCII value of char times the double, not 0 or 1.
You need to convert this to an integer first:
Integer.parseInt(Character.toString(str.charAt(16-1 - i))) * Math.pow(2, i)
Or, you can just:
Integer.parseInt(binaryString, 2)
People here have already answered what went wrong. Doing Math.pow(2, i) on a character produced inconsistent result.
If you are going to convert binary value to an Integer this could help you.
Integer.parseInt(binaryString, 2)
Where the value 2 is the radix value.
Java documentation and similar SO Discussion on the same topic is available here.
When you use str.charAt(16-1-i), you get back a char, which represents a single letter. So you don't get the number 0 or 1, but the corresponding letters. As letters are represented as integers in Java, you don't get a type error. The number to represent a 0 letter is 48, for 1 it's 49. To convert your letter into the correct number, you have to write (str.charAt(16-1-i)-48) instead of str.charAt(16-1-i).
Related
This question already has answers here:
Convert int to char in java
(18 answers)
Closed 1 year ago.
So what i understand is that if for example i have an int a = 49 and want to find out the ASCII equivalent to it, all i need to do is:
int a = 49;
System.out.println((char)a);
which has the Output: 1.
But how can i do this reversed? So lets say i have int a = 1 and i want the output to be 49?
I have already tried stuff like:
int a = 1;
System.out.println ((char)a);
But the output here is "." instead of 49.
This:
int a = 49;
System.out.println((char)a);
gives you the char whose internal value is 49, which is to say the unicode character '1'. There is no numerical conversion going on, it's just two ways to look at the same number.
In this:
int a = 1;
System.out.println((char)a);
you get the char whose internal value is 1, which is a unicode control character (ctrl/A, which probably won't be printed in any useful way). There is nothing there that can magically come up with the value 49.
If you had the character '1' then it's easy:
int a = '1';
System.out.println(a);
but this is practically the same as your first case; '1' and 49 are the same value.
I am obviously new to java. I have this assignment where I am supposed to write a program which performs arithmetic operations on numbers expressed as a character string.
I don't know where to start. I have tried googling, looking through my book, big java, in the relevant sections but can't seem to find helpful information.
I found a program that have completed the same assignment but I want to learn write my own and understand how to go about.
I can show you one of the methods that he used.
I have bolded a few comments where I get confused.
public static String add(String num1, String num2) {
while (num1.length() > num2.length()) {
num2 = "0" + num2;
}
while (num1.length() < num2.length()) {
num1 = "0" + num1;
}
int carry = 0; // whats the point of this?
String result = "";
// look at the for loop bellow. I don't understand why he is converting the strings to ints this
// way? this doesn't even return the correct inputed numbers?
for (int i = 1; i <= num1.length(); i++) {
int digit1 = Character.getNumericValue(num1.charAt(num1.length() - i));
int digit2 = Character.getNumericValue(num2.charAt(num2.length() - i));
int sum = digit1 + digit2 + carry;
carry = sum / 10;
result = (sum % 10) + result;
// why is he dividing the sum with 10? If the user inputs a 5, would't the result become 0.5
// which isn't a valid int value? this line is also confusing
}
if (carry > 0) {
result = carry + result;
}
return result;
}
Any explanation or even guidance to a page where I am trying to do is explained would be very appreciated.
I found a program that have completed the same assignment but I want to learn write my own and understand how to go about.
That is the right idea. I suggest that you stop looking at the code that you found. (I'm sure that your teachers don't want you to look up the answers on the internet, and you will learn more from your homework if you don't do it.)
So how to proceed?
(I am assuming that you are supposed to code the methods to do the arithmetic, and not just convert the entire string to a primitive number or BigInteger and use them to do the arithmetic.)
Here's my suggested approach:
What you are trying to program is the equivalent of doing long addition with a pencil and paper. Like you were taught in primary school. So I suggest that you think of that pencil-and-paper procedure as an algorithm and work out how to express it as Java code. The first step is to make sure that you have the steps of this algorithm clearly in your head.
Try to break the larger problem into smaller sub-problems. One sub-problem could be how to convert a character representing a decimal digit into an integer; e.g. how to convert '1' to 1. Next sub-problem is adding two numbers in the range 0 to 9 and dealing with the "carry". A final sub-problem is converting an integer in the range 0 to 9 into the corresponding character.
Write sample Java code fragments for each sub-problem. If you have been taught about writing methods, some of the code fragments could be expressed as Java methods.
Then you assemble the solutions to the sub-problems into a solution for the entire problem. For example, adding two (positive!) numbers represented as strings involves looping over the digits, starting at the "right hand" end.
As part of your program, write a collection of test cases that you can use to automate the checking. For example:
String test1 = add("8", "3");
if (!test1.equals("11")) {
System.out.println("test1 incorrect: expected '11' go '" +
test1 + "'");
}
Hints:
You can "explode" a String to a char[] using the toCharArray method. Or you could use charAt to get characters individually.
You can convert between a char representing a digit and an int using Character methods or with some simple arithmetic.
You can use + to concatenate a string and a character, or a character and a string. Or you can use a StringBuilder.
If you need to deal with signed numbers, strip off and remember the sign, do the appropriate computation, and put it back; e.g. "-123 + -456" is "- (123 + 456)".
If you need to do long multiplication and long division, you can build them up from long addition and long subtraction.
You can convert a number in String format to a number in numeric format by “long n = Long. parseLong(String)” or “Long n = Long.valueOf(String)”. Then just add 2 long variables using a + sign. It will throw NumberFormatException if the String is not a number but a character. Throw that exception back to the caller.
The first part of the code pads both numbers to equal lengths.
e.g. "45" + "789" will be padded to "045" + "789"
The for loop evaluates one character at a time, starting from the right hand most.
iteration 1 -> (right most)
5 + 9 -> 14
when you divide an integer with another integer, you will always get an integer.
hence carry = 14/10 = 1 (note: not 1.4, but 1, because an int cannot have decimal places)
and the remainder is 14 % 10 = 4 (mod operation)
we now concatenate this remainder into "result" (which is "" empty)
result = (14%10)+ result; // value of result is now "4"
iteration 2 -> (second right most)
4+8 + (carry) = 4 + 8 + 1 = 13
same thing, there is a carry of 13/10 = 1
and the remainder is 13%10 = 3
we concatenate the remainder into result ("4")
result = (13%10) + result = 3 +"4" = "34"
iteration 3->
0 + 7 + 1 = 8
this time 8/10 will give you 0 (hence carry = 0)
and 8%10 will give a remainder of 8.
result = 8 + "34" = "834"
after all the numbers have been evaluated, the code checks if there are anymore carry. if the value is more than 0, then that value is added to the front of the result.
I can't think of a better way to left pad an integer with zeroes without first converting it to a String. Is there a way to do this? I've found numerous questions regarding this but they all require a String conversion. I understand we can find the length with this approach:
int length = (num==0) ? 1 : (int)Math.log10(num) + 1;
However, this will still require me to convert it to a String and back afterwards. Surely, there's a better way?
No. An int represents a mathematical integer value, represented as 32 bits. The number 0001 is 1, and has a unique binary representation. Left-padded integers are not integers. they are Strings.
No. Numeric types cannot contain leading zeros. This a feature of the formatted textual representation i.e. Strings
Since you already have the length I'm guessing the leading zero's are simply for output, but ultimately your question was answered by the other two posters.
int length = (num==0) ? 1 : (int)Math.log10(num) + 1;
String zeros;
for(int i=0; i<length; i++) {
zeros = zeros.concat("0");
}
System.out.println(zeros + num);
I'm trying to figure out how I could use a java program to return the last 3 digits of an integer.
So for example if I had a number like 45678 how would I be able to return 678? Also how would I be able to determine that the length of this integer is 5 digits?
You can determine how many digits a number has by using Math.log10() (remember to Math.abs() if you're going to be dealing with negatives):
(int) Math.log10(45678) + 1 // 5
Using the modulo operator with Math.pow() can give you the last x digits of a number:
int x = 3;
45678 % Math.pow(10, x) // 678
String s = Integer.toString(45678);
s.substring(s.length() - 3); // first answer
s.length() == 5; // second answer
I have a program that I am working on which would effectively convert binary, decimal, or hex numbers to other formats (don't ask why I'm doing this, I honestly don't know). So far I only have a binary - decimal conversion going, and it works fine however whenever the binary number entered is 8 digits or more it crashes.
As far as I can tell when I input the number 10011001 it gets translated to scientific notation and becomes 1.0011001E7 which wouldn't really be a problem, except that the way I am converting the numbers involves creating a string with the same value as the number and breaking it into individual characters. Unfortunately, this means I have a string valued "1.0011001E7" instead of "10011001", so when I cut up the characters I hit the "." and the program doesn't know what to do when I try to make calculations with that. So basically my question comes down to this, how do I force it to use the not-scientific notation version for these calculations?
Thanks for all your help, and here is the code if it helps at all:
//This Splits A Single String Of Digits Into An Array Of Individual Digits
public float[] splitDigits(float fltInput){
//This Declares The Variables
String strInput = "" + fltInput;
float[] digit = new float[strInput.length() - 2];
int m = 0;
//This Declares The Array To Hold The Answer
for (m = 0; m < (strInput.length() - 2); m++){
digit[m] = Float.parseFloat(strInput.substring(m, m + 1)); //Breaks here
}
//This Returns The Answer
return digit;
}
Just use BigDecimal
BigDecimal num = new BigDecimal(fltInput);
String numWithNoExponents = num.toPlainString();
Note here the fltInput will be automatically converted to a double.