I am having issue with my algorithms to convert a decimal number to a binary number without using parsing, this is the relevant section of code:
public static void dtb(){
System.out.print("\nDenary number to convert?(lower than 255): "); //eight bit conversion
int num = sc.nextInt();
int decVal = 128;
int saveNum = num; //save point for the first input
int[] arr;
arr = new int[8];
do{
if (num - decVal > 0){ //binary to decimal
num = num - decVal;
arr[x] = 1;
} else arr[x] = 0;
decVal = decVal / 2;
x++;
} while (decVal != 1);
System.out.print("\nBinary value of "+saveNum+" is: "+arr[0]+arr[1]+arr[2]+arr[3]+arr[4]+arr[5]+arr[6]+arr[7]);
}
x is declared initialized statically, therefore out of view.I also know where the error is but I cant work out the right way to do it, hence the ask for help. I am also fairly new so any help on other method will be appreciated. Thank you for any help.
Example of output = (input=42) 00101000
You need to compare whether num - decVal is greater than or equal to 0. Because you have >, you are missing the case then it's equal to 0 and you're missing a 1 bit.
if (num - decVal >= 0){
Also, you'll need to loop while decVal is not equal to 0, instead of 1, or else you'll miss the last bit on odd numbers.
} while (decVal != 0);
Output with changes:
Binary value of 42 is: 00101010
Binary value of 43 is: 00101011
Related
i'm just trying to make a decimal to binary converter in java, what i want to display is suppose to be like this:
Binary 41 is 00101001
But, here's display what i just made:
Binary 41 is: 101001
And here's my code:
public void convertBinary(int num){
int binary[] = new int[40];
int index = 0;
while(num > 0){
binary[index++] = num % 2;
num/=2;
}
for(int i = index-1; i >= 0; i--){
System.out.print(binary[i]);
}
What can i do, to make a display 8 bit binary? I appreciate it so much for all answer you gave to me, thank you
Use
System.out.format("%08d%n", binary[i]);
instead of
System.out.print(binary[i]);
The "%08d%n" in System.out.format("%08d%n", binary[i]); formats the output as 8 digit integer.
Note:
Here are some more examples:
https://docs.oracle.com/javase/tutorial/java/data/numberformat.html
If num is guaranteed to be less than 256, the simplest change for your existing code is to change the loop condition to index < 8
while(index < 8){
binary[index++] = num % 2;
num/=2;
}
This directly expresses the desire to have 8 digits. That is, you simply do not stop when you have converted all non-zero bits.
int t;
byte val = 123;
for(t = 128; t > 0; t = t/2){
if((val & t) != 0) System.out.print("1 ");
else System.out.print("0 ");
}
I'd like to know how to remove numbers from an integer. For example, if I have the number 23875326, I want to remove the odd numbers, and get the result of 2826.
I've been trying to break each number to check if it's even or odd using a while loop, but I don't know how to merge the numbers into one integer. One important thing is, I'd like to do it without using strings, as it doesn't teach me anything new that way.
I actually think that dealing with a string of numbers is preferable, not only from a code readability point of view, but also possibly from a performance view. That being said, if we absolutely cannot use strings here, then it is still possible to work directly with the integer input.
We can examine each tens digit of the input number using num % 10. Should that digit be even, we can add it to the output number, otherwise do not add it. Note that at each iteration we need to scale the digit by 10 to the correct exponent.
Here is a working code snippet:
int length = (int) (Math.log10(num) + 1); // finds the number of digits
int output = 0;
int counter = 0;
for (int i=0; i < length; ++i) {
if ((num % 10) % 2 == 0) {
output += (num % 10) * Math.pow(10, counter);
++counter;
}
num = num / 10;
}
System.out.println(output);
2826
Demo
I used #Tim Biegeleisen code and changed it a bit, removed some code and changed the for loop to while loop:
int output = 0;
int counter = 0;
System.out.println("Enter a number");
int num = s.nextInt();
while (num != 0) {
if ((num % 10) % 2 == 0) {
output += (num % 10) * Math.pow(10, counter);
++counter;
}
num = num / 10;
}
System.out.println(output);`
For this lab, you will enter two numbers in base ten and translate
them to binary. You will then add the numbers in binary and print out
the result. All numbers entered will be between 0 and 255, inclusive,
and binary output is limited to 8 bits. This means that the sum of the
two added numbers will also be limited to 8 bits. If the sum of the
two numbers is more than 8 bits, please print the first 8 digits of
the sum and the message "Error: overflow". Your program should
represent binary numbers using integer arrays, with the ones digit
(2^0) stored at index 0, the twos digit (2^1) stored at index 1, all
the way up to the 2^7 digit stored at index 7. Your program should
include the following methods:
int[] convertToBinary(int b) Translates the parameter to a binary value and returns it stored as an array of ints.
void printBin(int b[]) Outputs the binary number stored in the array on one line. Please note, there should be exactly one space
between each output 0 or 1.
int[] addBin(int a[], int b[]) Adds the two binary numbers stored in the arrays, and returns the sum in a new array of ints.
When entering my code into CodeRunner (which tests the code and returns a grade back depending on the results of each test) I cannot seem to pass one of the tests. This is the message that I am getting:
*You had 43 out of 44 tests pass correctly. Your score is 97%.
The tests that failed were: Test: addBin() method Incorrect: Incorrect number returned*
Heres my code:
import java.util.Scanner;
class Main {
public static int[] convertToBinary(int a) {
int[] bin = {0, 0, 0, 0, 0, 0, 0, 0};
for (int i = bin.length - 1; i >= 0; i--) {
bin[i] = a % 2;
a = a / 2;
}
return bin;
}
public static void printBin(int[] b) {
int z;
for (z = 0; z < b.length; z++) {
System.out.print(b[z] + " ");
}
System.out.println();
}
public static int[] addBin(int[] c, int[] d) {
int[] added = new int[8];
int remain = 0;
for (int x = added.length - 1; x >= 0; x--) {
added[x] = (c[x] + d[x] + remain) % 2;
remain = (c[x] + d[x] + remain) / 2;
}
if (added[0] + c[0] + d[0] == 1) {
added[0] = 1;
} else if ((added[0] + c[0] + d[0] == 2) || (added[0] + c[0] + d[0] == 3)) {
System.out.println("Error: overflow");
}
return added;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a base ten number between 0 and 255, inclusive.");
int num1 = scan.nextInt();
System.out.println("Enter a base ten number between 0 and 255, inclusive.");
int num2 = scan.nextInt();
int[] bin;
bin = convertToBinary(num1);
System.out.println("First binary number:");
printBin(bin);
int[] bin1 = bin;
bin = convertToBinary(num2);
System.out.println("Second binary number:");
printBin(bin);
int[] bin2 = bin;
System.out.println("Added:");
{
printBin(addBin(bin1, bin2));
}
}
}
If anyone could take a look at my code above and see if they could tell me what needs to be changed to fix the addbin() method so that it passes all of the tests, that'd be great! Any help is greatly appreciated even if you are not sure it would work! Thanks!
Hi first of all pardon my English but i guess your assignment accepts 1 and 255 too. So i added two of them and get 1 0 0 0 0 0 0 0 in your code. But i think it need to be 0 0 0 0 0 0 0 0 with an overflow error. So i changed your code a little bit.
public static int[] addBin(int[] c, int[] d) {
int[] added = new int[8];
int remain = 0;
for (int x = added.length - 1; x >= 0; x--) {
added[x] = (c[x] + d[x] + remain) % 2;
remain = (c[x] + d[x] + remain) / 2;
}
if (remain!=0) {
System.out.println("Error: overflow");
}
return added;
}
It's my first answer on the site so i hope it works for your test
I converted a decimal integer to binary and that binary integer when I'm trying to convert to a string is giving me 1 as the answer always when it should give the value of the string.
while(a>0)
{
b = a%2;
n = b;
a = a/2;
System.out.print(n);
}
String m = Integer.toString(n);
System.out.print(m);
Any corrections and suggestions would be much appreciated.
Thanks!
On every loop step, you have these two statements:
b = a % 2;
n = b;
Think about why all the possible values of n are 0 and 1?
It's because n copies the value of b, which is the value of a modulo 2, which is always 0 or 1.
The last value of n will be the left-most bit of the binary representation of a, which will be always 1 (unless a is 0) and this is why you always get 1 when printing m.
When you use
n = b;
you are replacing the value of n each time. What you want it to accumulate the bits in n. The simplest way to do this is to use a StringBuilder.
StringBuilder sb = new StringBuilder();
while (a > 0) {
int lowest = a & 1;
sb.insert(0, lowest);
a = a >>> 1; // shift the bits down by 1.
}
String m = sb.toString();
System.out.print(m);
This will do the same thing as Integer.toString(a, 2)
I have to make a multiplication function without the * or / operators. I have already made a method like this.
for(int i=0; i < number1; i++){
result += number2;
}
System.Out.println(result);
Now, here is my problem: It was fine until my lecturer change the topic, where the multiplication method must be can multiply decimal value. I had no idea how I can make multiplication method which can work on decimal value with just + and - operator.
yeah you can use log for the multiplication.
log(a*b)=log(a)+log(b)
and then find out the exponential value of log(a)+log(b)
and then you can convert the sign..
for example:
-9*8=-72
log(9*8)=log(9)+log(8)=2.19+2.07=4.27
e^4.27=72
now there is only one -ve no. then it is -72
else it's 72
I'm writing the function for:
void multiply(int num1,int num2)
{
int counter=0;
if(num1<0)
{counter++;num1+=num1+num1;}
if(num2<0)
{counter++;num2+=num2+num2;}
double res=Math.log(num1)+Math.log(num2);
int result=(int)Math.exp(res);
if(counter%2==0)
System.out.println("the result is:"+result);
else
System.out.println("the result is:-"+result);
}
hope this will help you....
You take the decimal numbers and move the decimal point step by step until there is an int left: 0.041 -> 1. step 0.41 -> 2. step 4.1 -> 3. step 41
multiplying 0.041 * 3 could be done by doing the above step 3 times, multiplying 41 * 3 = 123. For the result you take the 123 and undu the steps: 1. 12.3, 2. 1.23, 3. 0.123. There is your result: 0.123 = 0.041 * 3.
Edit:
To determine the number of decimals for each number, you might find the answer in this question: How many decimal Places in A Double (Java)
Answers show within others two ways to solve this quite easy: putting the number to a String and checking where in this String the "."-DecimalPoint occurs, or using the BigDecimal type which has a scale()-Method returning the number of decimals.
You shouldn't expect whole perfect code: But here is a hint to achieve this.
Try to use recursion technique instead for loops.
public double multiplyMe(double x, double y)
{
if(y == 0 || x == 0)
return 0;
if(y > 0 && x > 0 )
return (x + multiplyMe(x, y-1)); // multiply positive
if(y < 0 || x < 0 )
return - multiplyMe(x, -y); // multiply negative
}
one more way by using log:
10 raise to power ( sum of log10(x) and log10(y) )
This approach might be easier to understand. You have to add a b times, or equivalently, b a times. In addition, you need to handle 4 different cases where a and b can be either positive or negative.
public int multiply(int a, int b){
int result = 0;
if (a < 0 && b < 0){
for (int i = a; i <= -1; i++)
result-=b;
}
else if (a < 0){
for (int i = 1; i <= b; i++)
result+=a;
}
else if (b < 0){
for (int i = 1; i <= a; i++)
result+=b;
}
else {
for (int i = 1; i <= b; i++)
result+=a;
}
return result;
}
public static void main(String[] args){
System.out.println(multiply(3,-13)); // -39
}