Print 8 bit binary conversion in java - java

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 ");
}

Related

The sum of all odd digits of an input [duplicate]

This question already has answers here:
How do I find the sum of all odd digits of user input numeric string?
(5 answers)
Closed 2 years ago.
How to compute the sum of all 'odd digits of an input' using 'loop'. (For example, if the input is 32677, the sum would be 3 + 7 + 7 = 17.)
I can't quite figure out how to do that, can someone please help me out. This is what I have done so far, I don't know how to complete it or whether I have its right or wrong.
Any help would be appreciated!
System.out.println("Enter a number: ");
String input = in.nextLine();
int length = input.length();
int sum = 0;
int digits = 0;
for (int i = 0; i < length; i++) {
if (length % 2 == 1) {
digits += i;
sum = digits++;
}
}
System.out.println(sum);
Here comes a Java8-based solution:
final int result = input.chars()//make a stream of chars from string
.mapToObj(String::valueOf) // make every character a String to be able to use parseInt later
.mapToInt(Integer::parseInt) // transform character in int
.filter(i -> i % 2 == 1) // filter out even numbers
.sum();
You don't need to use String if your input is not so long.
also for safe side use long datatype.
Here is the working code with comments (explain each step).
long sumOddDigits(long value){
long temp = value; // copy in temp variable
long sum = 0;
while(temp > 0){
int digit = temp%10; // get last digit of number. example: 227 gives 7.
temp = temp / 10; // remove that last digit from number.227 will be 22.
if(digit % 2 == 1){
sum += digit;
}
}
return sum;
}
Your interpretation of the digits inside of input is not working this way.
System.out.println("Enter a number: ");
String input = in.nextLine();
int length = input.length();
int sum = 0;
for (int i = 0; i < length; i++) {
int digit = input.charAt(i) - '0';
if (digit % 2 == 1) {
System.out.println("Add digit: " + digit);
sum += digit;
}
}
System.out.println(sum);
In your loop, use Integer.parseInt(input.charAt(i)) to get the number at position i.
if(length%2==1){ that doesn't make sense here. You want to check if your number is odd, not the length of your string.

Removing numbers from integer

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);`

Mathematically calculating decimal to binary (java)

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

multiplying using + and - in java

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
}

How to find single digit from a set of number by doing product of each numbers in java

I have a number like 99
now I need to get a single digit number like -
9*9 = 81
8*1 = 8
ex2:
3456 3*4*5*6
360 3*6*0
What will be the efficient way to get the output beside change the number to character/string then multiply with each adjacent .
Let me make the problem little more complex , what if I want to get the number of steps required to make the N to a single digit , then recursion may loose the steps and need to be done in a single method only
Presuming those are ints, you can use division and modulus by the base (10):
81 / 10 = 8
81 % 10 = 1
For the second example, you'd want to use a while (X >= 10) loop.
This recursive function should do it...
int packDown( int num ) {
if( num < 10 ) return num ;
int pack = 1 ;
while( num > 0 ) {
pack *= num % 10 ;
num /= 10 ;
}
return packDown( pack ) ;
}
public static int digitMultiply(int number) {
int answer = 1;
while (number > 0) {
answer=answer*(number % 10);
number = number / 10;
}
return answer;
}
hope it helps!! simple algorithm to multiply..
The following single recursive method should work also:
int multDig(int number){
if(number >= 10)
return multDig((number%10) * multDig(number/10));
else
return number;
}

Categories

Resources