Im having trouble converting binary to a decimal. We have to use a function for the conversion and do it by hand rather than use a predefined function. This is what I have so far, I know it is a mess but I am stuck on how to fix it. Thanks!
import java.util.Scanner;
public class BinaryConversion {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inString;
int decimal;
System.out.println("Enter a binary number: ");
inString = input.nextLine();
while (!"-1".equals(inString)) {
int i;
int binaryLength;
binaryLength = inString.length();
public static int binaryToDecimal (String binaryString) {
for (i = binaryLength - 1, decimal = 0; i >= 0; i--) {
if (inString.charAt(i) == '1')
decimal = decimal + Math.pow(2,inString.length() - 1 - i);
}
return (int) decimal;
}
System.out.println(decimal);
System.out.println("Enter a binary number: ");
inString = input.nextLine();
}
System.out.println("All set !");
}
}
To use a function, as your assignment requires, you have to write the function outside the main method, and then include a statement that calls the function. So move this above the line that says public static void main:
public static int binaryToDecimal (String binaryString) {
for (i = binaryLength - 1, decimal = 0; i >= 0; i--) {
if (inString.charAt(i) == '1')
decimal = decimal + Math.pow(2,inString.length() - 1 - i);
}
return (int) decimal;
}
Also, each function or method (including main) has its own variables that it uses, called local variables; but the local variables that each function uses are its own separate copies. Thus, the above function won't be able to use the binaryLength or decimal variabes belonging to main. You'll need to declare them inside binaryToDecimal:
public static int binaryToDecimal (String binaryString) {
int decimal;
int binaryLength;
for (i = binaryLength - 1, decimal = 0; i >= 0; i--) {
if (inString.charAt(i) == '1')
decimal = decimal + Math.pow(2,inString.length() - 1 - i);
}
return (int) decimal;
}
Also, this function won't be able to access main's inString, but the idea is that you've given the function the string you want to work with, which it refers to as binaryString. So change inString to binaryString in the function:
public static int binaryToDecimal (String binaryString) {
int decimal;
int binaryLength;
for (i = binaryLength - 1, decimal = 0; i >= 0; i--) {
if (binaryString.charAt(i) == '1')
decimal = decimal + Math.pow(2,binaryString.length() - 1 - i);
}
return (int) decimal;
}
And also note that the binaryLength and decimal variables are totally unrelated to the variables of the same name in main. That means that when you assigned binaryLength in main, that has no effect on binaryLength in binaryToDecimal. You'll need to assign it in the function. Change int binaryLength; to
int binaryLength = binaryString.length();
Finally, in order to use the function, main will need to call it. Put this in the main function:
decimal = binaryToDecimal(inString);
When main executes that, it will call the function and tell it to work with inString. The function will call that binaryString, though. The function will return a result, and then main will assign that result to the variable decimal--that means the local variable decimal that belongs to main, since the above statement is inside main.
I don't know if this will make your whole program work. (It should, but I'm not sure.) But I'm just trying to explain the details of how to use functions.
The confusing part is with the Math.pow, and its complicated arguments, where off-by-one errors are easily made.
Yet, if we have a number at base 10, like
123
its value is
(((0*10)+1)*10+2)*10+3
This looks complex, but note the easy pattern: Starting out with 0, we go through the digits. As long as we have another dgit, we multiply the previous result by the base and add the digit value. That's all! No Math.pow, no complex index calculations.
Hence:
String s = "1010";
int value = 0;
int base = 2;
for (i=0; i < s.length(); s++) {
char c = s.charAt(i);
value = value * base;
value = value + c - '0';
}
When I cleaned up your code, it worked just fine -
public static int binaryToDecimal(String binaryString) {
int binaryLength = binaryString.length();
int decimal = 0;
for (int i = binaryLength - 1; i >= 0; i--) {
if (binaryString.charAt(i) == '1') {
decimal += Math.pow(2, binaryLength - 1 - i);
}
}
return decimal;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String inString = input.nextLine();
while (!"-1".equals(inString)) {
System.out.println(binaryToDecimal(inString));
System.out.println("Enter a binary number: ");
inString = input.nextLine();
}
System.out.println("All set !");
}
Output
Enter a binary number:
01
1
Enter a binary number:
10
2
Enter a binary number:
-1
All set !
Here's the function after a little clean up.
public static int binaryToDecimal (String binaryString) {
int decimal = 0;
int base = 2;
for (int i = binaryString.length() - 1; i >= 0; i--) {
if (binaryString.charAt(i) == '1')
decimal += Math.pow(base,i);
}
return decimal;
}
Related
I tried to create a code to take in a whole number in Java and output it in binary. The problem would seem that the binary is printing out backward. For instance, 6 should output as 011 but comes out as 110.
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
int userNum;
Scanner in =new Scanner(System. in );
userNum = in.nextInt();
binary(userNum);
System.out.print("\n");
}
private static void binary(int userNum) {
int remainder;
while (userNum <= 1) {
System.out.print(userNum);
return;
}
remainder = userNum % 2;
binary(userNum >> 1);
System.out.print(remainder);
}
}
I tried incorporating a push stack to push the remainder into a stack that I can pull later, but couldn't quite get it to land.
private static void reverse(int userNum) {
String backwards;
while (userNum >= 0) {
backwards.push(int userNum);
System.out.println(backwards);
return;
}
}
It is part of a class assignment which asks the following.
Write a program that takes in a positive integer as input, and outputs a string of 1's and 0's representing the integer in binary. For an integer x, the algorithm is:
As long as x is greater than 0
Output x % 2 (remainder is either 0 or 1)
x = x / 2
Note: The above algorithm outputs the 0's and 1's in reverse order.
Ex: If the input is:
6
the output is:
011
6 in binary is 110; the algorithm outputs the bits in reverse.
These are the tests the program applies and my results.
Input 6
Your output binary is:110
Expected output 011
Input 19
Your output 10011
Expected output 11001
Input 255
Your output 11111111
Expected output 11111111
Any help or guidance in this, I would be greatly appreciative of it.
Per the requirement and not taking into consideration of negative numbers
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
int userNum;
Scanner scnr = new Scanner(System.in);
userNum = scnr.nextInt();
while(userNum > 0){
System.out.print(userNum % 2);
userNum = userNum / 2;
}
System.out.print("\n");
}
}
First using predefined method then a custom one.
public class IntToBinary {
public static void main(String[] args) {
int decimalNumber = 10;
System.out.println(Integer.toBinaryString(decimalNumber));
System.out.println(convertBinary(10));
}
public static String convertBinary(int num) {
StringBuilder sb = new StringBuilder();
int binary[] = new int[40];
int index = 0;
while (num > 0) {
binary[index++] = num % 2;
num = num / 2;
}
for (int i = index - 1; i >= 0; i--) {
sb.append(binary[i]);
}
return sb.toString();
}
}
Your program appears to work fine for positive values. However it does not handle negative numbers which have their own unique binary representation known as two's complement. You could do something like the following to accommodate:
private static void binary(int userNum) {
int remainder;
// while (userNum <= 1) {
// System.out.print(userNum);
// return;
// }
if (userNum == 0) {
return;
}
// simply mask off the bit instead of dividing by two
remainder = userNum & 1;
// and shift right thru the sign bit
binary(userNum >>> 1);
System.out.print(remainder);
}
}
binary(-6));
prints
11111111111111111111111111111010
And the reason these printed out in proper order is because your routine is recursive. That is a natural behavior of printing the values stored in the stack from a recursive procedure.
import java.util.Scanner;
public class Reverse_BinaryNum {
public static void main(String[] args) {
/* Type your code here. */
Scanner scnr = new Scanner(System.in);
int inputNum;
System.out.println("Enter the Digit : ");
inputNum = scnr.nextInt();
System.out.println("The Reverse Binary for the given Digit is : ");
while (inputNum > 0) {
System.out.print(inputNum % 2);
inputNum = inputNum / 2;
}
scnr.close();
}
}
I need to write a program to receive a number from the user, use a user=defined method to reverse the number, then return the number as an integer. Below is what I have so far. I am trying to see if I can take each individual digit from the array and somehow put them together as an integer. Do I need to put them together as a string and then convert it to integer? or is there a simpler way all together to do this?
import java.util.*;
public class UserDefinedMethods
{
static Scanner keyboard = new Scanner(System.in);
public static int reverseDigits(int num)
{
int reverse[];
int i = 0;
int out = 0;
do
{
if (num < 0)
num = (num * -1);
reverse[i] = num % 10;
num = num/10;
i++;
}
while (num > 0);
out =
return reverse; //HERE IS MY PROBLEM I BELEIVE.
}
public static void main(String[] args)
{
int number = 0;
int output = 0;
System.out.println("Please enter a number:");
number = keyboard.nextInt();
output = reverseDigits(number);
System.out.println(output);
}
}
Reversing an int can be done as follows:
Set result to zero.
If the number is zero, return the result that you have so far
Add a trailing zero to the result
Replace trailing zero with the last digit of the original number
Drop the last digit of the original number
Go to step 2.
Here is how to do selected things in Java:
To get the last digit use int lastDigit = number % 10;
To drop the last digit use number /= 10;
To add zero as the last digit of the result use result *= 10;
To replace the trailing last digit use result += lastDigit;
Demo.
Ok first off, you're attempting to return the array reverse, but your method declaration is set to return an int (not int[]). Secondly, your code can be simplified as follows:
public static int reverseDigits(int num){
int reverse = 0;
while(num != 0){
reverse *= 10;
reverse += (num % 10);
num /= 10;
}
return reverse;
}
Hope this helps! :)
I have to create a java program that converts binary to decimal using the following steps. Being new at this I did something, but I don't know what I did wrong or how to continue.
public class BinaryToDecimal {
public static void main(String args[]){
long sum = 0;
int result;
String s = "1001010101011010111001011101010101010101";
for(int i = s.length()-1; i <= 0; i--){
result = (int)Math.pow(2, i);
if(s.charAt(i) == '1')
sum=sum + result;
}
System.out.println(sum);
}
}
Use a loop to read (charAt()) each digit (0/1 char) in the input string, scanning from right to left;
Use the loop to build the required powers of 2;
Use a conditional statement to deal with 0 and 1 separately;
Debug using simple input, e.g. 1, 10, 101, and print intermediate values in the loop.
Use your program to find the decimal value of the following binary number:
1001010101011010111001011101010101010101
Do this only if your decimal value is at most 2147483647 or the maximum value an int can be in Java. If you don't know, just check the length of your string. If it's less than or equal to 32 i.e. 4 bytes, then you can use parseInt.:
int decimalValue = Integer.parseInt(s, 2);
Refer HERE for more info on the Integer.parseInt();
But if it's more, you can use your code. I modified your loop which is where your problem was:
String s = "1001010101011010111001011101010101010101";
long result = 0;
for(int i = 0; i < s.length(); i++){
result = (long) (result + (s.charAt(i)-'0' )* Math.pow(2, s.length()-i-1));
}
System.out.println(result);
The first thing I notice is that your binary number has more than 32 bits. This cannot be represented in the space of an int, and will result in overflow.
As a simpler answer, I ran the following and got the correct value at the end, it just uses simple bit shifts.
For each index in the string, if the character is 1, it sets the corresponding bit in the result.
public class BinaryToDecimal {
public static void main(String[] args) {
long sum;
String bin = "1001010101011010111001011101010101010101";
sum = 0;
for (int i = 0; i < bin.length(); i++) {
char a = bin.charAt(i);
if (a == '1') {
sum |= 0x01;
}
sum <<= 1;
}
sum >>= 1;
System.out.println(sum);
}
}
The loop runs from i = s.length()-1 until i <= 0. This should be i>=0.
The next problem is "int result". It works fine with result as a long ;) (Reason: You calculate a 40-bit value at the MostSignificantBit, but Integers only use 32-bit)
Also: You start at the rightmost Bit with i=s.length()-1. But the power that you calculate for it is 2^(s.length()-1) though it should be 2^0=1.
The solution is: result = (long)Math.pow(2, s.length()-1-i)
Edit:
I really like the solution of user2316981 because of its clear structure (without Math.pow, should be faster by using shift instead). And loops from 0 to MSB as I do with Double&Add algorithm. Can't comment on it yet, but thanks for the reminder ;)
import java.util.*;
import java.lang.Math;
class deci {
int convert(int n) {
int tem=1,power=0;
int decimal=0;
for (int j=0;j<n;j++) {
if(n==0) {
break;
} else {
while(n>0) {
tem=n%10;
decimal+=(tem*(Math.pow(2,power)));
n=n/10;
power++;
}
}
}
return decimal;
}
public static void main(String args[]) {
System.out.print("enter the binary no");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
deci dc=new deci();
int i=dc.convert(n);
System.out.print(i);
}
}
I have numeric input (11 digits), and I need to perform some operations on each digit (example: multiply 1st by 5, 2nd by 3, etc.). How can I do so in Java? Is there a simple way to access single letter / digit? Is there another way to do it?
If you don't want to convert the number to a string, then there is a simple trick.
digit = number % 10
will give you the right most digit.
number = number / 10
Will remove the right most digit from the number.
So you can run in a loop until the number reaches 0.
while(0 < number)
{
int digit = number % 10;
number = number / 10;
// do here an operation on the digits
}
You can use a for loop to help you count. For example
for(int index = 0; 0 < number; ++index, number /= 10)
{
int digit = number % 10;
// do an operation on the number according to the 'index' variable
}
Here is a similar StackOverFlow question on a similar question
Well there are many ways you can do it like :
int a = 12345;
int b;
while(a>0)
{
b = a%10;
System.out.print(b + " ");
a = a/10;
}
Here it gives you the digits in reverse order like you will get b=5 then b=4....
You can just manipulate them
Other way
int d = 12345;
String str = String.valueOf(d);
for(int i=0;i<str.length();i++)
{
char c = str.charAt(i);
System.out.print(Character.getNumericValue(c) * 10 + " ");
}
Or
char c[] = str.toCharArray();
for(Character ch : c)
{
System.out.print(Character.getNumericValue(ch) * 2 + " ");
}
You can use .charAt() to get a character from a string. Then using Character.getNumericValue() you can convert the character to an integer.
Like this:
String string = "1434347633";
int digit1 = Character.getNumericValue(string.charAt(1));
Convert that number input to String data type so that you can interpret it as a String.
int numbers = 1122334455; // integer won't be able to save this much data,
// just for example ok,
String numberString = numbers.toString();
foreach (char number in numberString) {
// do work on each of the single character in the string.
}
You should work them out, depending on the some condition.
If you want to access the digits by index without converting to a string, you can use these two functions length and digitAt:
public class DigitAt {
public static int length(long v) {
return (int) Math.ceil(Math.log10(v));
}
public static int digitAt(long v, int digit) {
return (int) ((v / (long) Math.pow(10, length(v) - digit - 1)) % 10);
}
public static void main(String[] args) {
System.out.println("Digits: " + length(1234567));
System.out.println(digitAt(1234567, 0));
System.out.println(digitAt(1234567, 1));
System.out.println(digitAt(1234567, 6));
}
}
public String stringAfterOperations(String digits) {
ArrayList<Integer> z = new ArrayList<Integer>();
for(Character c: digits.toCharArray()) {
z.add(Character.getNumericValue(c));
}
//TODO Set your own operations inside this "for"
for(int i=0; i<z.size(); i++){
if(i == 1){
z.set(i, z.get(i)*4);
}
else if(i == 7){
z.set(i, z.get(i)/3);
}
else {
z.set(i, z.get(i)+2);
}
}
String newString = "";
for(Integer i: z){
newString += i;
}
return newString;
}
I'm trying to write a code that converts a number to binary, and this is what I wrote. It gives me couple of errors in Eclipse, which I don't understand.
What's wrong with that? Any other suggestions? I'd like to learn and hear for any comments for fixing it. Thank you.
public class NumberConverte {
public static void main(String[] args) {
int i = Integer.parseInt(args);
public static void Binary(int int1){
System.out.println(int1 + "in binary is");
do {
System.out.println(i mod 2);
} while (int1>0);
}
}
}
The error messages:
The method parseInt(String) in the type Integer is not applicable for the arguments (String[])
Multiple markers at this line
Syntax error on token "(", ; expected
Syntax error on token ")", ; expected
void is an invalid type for the variable Binary
Multiple markers at this line
Syntax error on token "mod", invalid AssignmentOperator
Syntax error on token "mod", invalid AssignmentOperator.
Integer.toBinaryString(int) should do the trick !
And by the way, correct your syntax, if you're using Eclipse I'm sure he's complaining about a lot of error.
Working code :
public class NumberConverter {
public static void main(String[] args) {
int i = Integer.parseInt(args[0]);
toBinary(i);
}
public static void toBinary(int int1){
System.out.println(int1 + " in binary is");
System.out.println(Integer.toBinaryString(int1));
}
}
Maybe you don't want to use toBinaryString(). You said that you are learning at the moment, so you can do it yourself like this:
/*
F:\>java A 123
123
1 1 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0
*/
public class A {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
System.out.println(a);
int bit=1;
for(int i=0; i<32; i++) {
System.out.print(" "+(((a&bit)==0)?0:1));
bit*=2;
}
}
}
I suggest you get your program to compile first in your IDE. If you are not using an IDE I suggest you get a free one. This will show you where your errors are and I suggest you correct the errors until it compiles before worring about how to improve it.
There are a two main issues you need to address:
Don't declare a method inside another method.
Your loop will never end.
For the first, people have already pointed out how to write that method. Note that normal method names in java are usually spelled with the first letter lowercase.
For the second, you're never changing the value of int1, so you'll end up printing the LSB of the input in a tight loop. Try something like:
do {
System.out.println(int1 & 1);
int1 = int1 >> 1;
} while (int1 > 0);
Explanation:
int1 & 1: that's a binary and. It "selects" the smallest bit (LSB), i.e. (a & 1) is one for odd numbers, zero for even numbers.
int1 >> 1: that's a right shift. It moves all the bits down one slot (>> 3 would move down 3 slots). LSB (bit 0) is discarded, bit 1 becomes LSB, bit 2 becomes bit one, etc... (a>>0) does nothing at all, leaves a intact.
Then you'll notice that you're printing the digits in the "wrong order" - it's more natural to have them printed MSB to LSB. You're outputting in reverse. To fix that, you'll probably be better off with a for loop, checking each bit from MSB to LSB.
The idea for the for loop would be to look at each of the 32 bits in the int, starting with the MSB so that they are printed left to right. Something like this
for (i=31; i>=0; i--) {
if (int1 & (1<<i)) {
// i-th bit is set
System.out.print("1");
} else {
// i-th bit is clear
System.out.print("0");
}
}
1<<i is a left shift. Similar to the right shift, but in the other direction. (I haven't tested this at all.)
Once you get that to work, I suggest as a further exercise that you try doing the same thing but do not print out the leading zeroes.
For starters you've declared a method inside a method. The main method is the method that runs first when you run your class. ParseInt takes a string, whereas args is an Array of strings, so we need to take the first (0-based) index of the array.
mod is not a valid operator, the syntax you wanted was %
You can use System.out.print to print on the same line rather than println
Try these corrections and let me know how you get on:
public class NumberConverter {
public static void main(String[] args) {
int i = Integer.parseInt(args[0]);
Binary(i);
}
public static void Binary(int int1){
System.out.println(int1 + " in binary is ");
do {
System.out.print(int1 % 2);
int1 /= 2;
} while (int1 > 0);
}
}
Here is a small bittesting code I made for Android.
int myres = bitTest(7, 128);
public int bitTest(int bit,int value)
{
int res = 0;
int i = 0;
while (i <= bit) {
res = (value & 1);
value = value >> 1;
i++;
}
return res;
}
Best Regards
Mikael Andersson
StringBuffer sb = new StringBuffer("");
void breakNumber(int num){
if(num == 0 || num == 1){
System.out.println(num);
}else{
int modr = num % 2;
sb.append(modr);
int divr = num / 2;
if(divr > 1){
breakNumber(divr);
}else{
sb.append(modr);
StringBuffer sbr =sb.reverse();
System.out.println(sbr.toString());
}
}
}
package gg;
import java.util.*;
public class Gg {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean flag = true;
while (flag) {
menu();
int n = in.nextInt();
switch (n) {
case 1:
System.out.println("enter an integer decimal number : ");
int d = in.nextInt();
System.out.print("the answer is ");
DTB(d);
System.out.println();
break;
case 2:
System.out.println("enter a binary number : ");
int b = in.nextInt();
System.out.print("the answer is " + BTD(b));
System.out.println();
break;
case 3:
flag = false;
break;
}
}
}
public static void menu() {
System.out.println("1.convert decimal to binary : ");
System.out.println("2.convert binary to decimal : ");
System.out.println("3.exit");
}
public static void DTB(int x) {
int n = 0;
int y = x;
while (y > 0) {
y /= 2;
n++;
}
int s[] = new int[n];
int i = 0;
while (x > 0) {
s[i] = x % 2;
x /= 2;
i++;
}
for (int j = s.length - 1; j >= 0; j--) {
System.out.print(s[j]);
}
}
public static int BTD(int x) {
int y = 2;
int sum = 0;
double k = 1;
int c = 0;
while (x > 0) {
double z = x % 10;
x /= 10;
k = Math.pow(y, c);
c++;
k *= z;
sum += k;
}
return sum;
}
}