Re: Need help to convert
To: comp.lang.java.gui
On Feb 24, 5:17 am, "Jeff Higgins" <oohigg...@yahoo.com> wrote:
Katak wrote:
Lew suggested the String.charAt() method but,
if this is an exercize in converting
number representations by hand
see the comment;
else
why?YourConverter:MyConverter
import java.util.Scanner;
public class YourConverter {
public static void main(String[] args) {
String bin;
int result = 0;
double power = 0;
System.out.println("Enter a binary number: ");
Scanner input = new Scanner(System.in);
bin = input.nextLine();
//See Roedy Green's mindprod site for details on
//converting binary to decimal numbers
for (int i = bin.length(); i == 0; i--) {
double cubed = Math.pow(2, power);
result += ((bin.charAt(i) - 48) * (cubed));
power++;
}
System.out.print("Decimal = " + result);
}
}
Enter a binary number:
1101
Decimal = 0
public class MyConverter {
public static void main(String[] args) {
String hexString = "4341464542414245";
Long dec = Long.valueOf(hexString, 16);
String bin = Long.toBinaryString(dec);
System.out.println(dec + " : " + hexString);
System.out.println(bin);
}
}
4846231937305625157 :
4341464542414245
1000011010000010100011001
00010101000010010000010100001001000101
Thanks. I've fixed a lil bit of it and it works well now. Updated
codings are as below.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class BinaryToDecimal {
private static BufferedReader stdin= new BufferedReader(new
InputStreamReader(System.in));
public static void main(String[]args) throws IOException{
int result = 0;
double power = 0;
System.out.println("Enter a binary number: ");
String bin = stdin.readLine();
System.out.println("Binary = " + bin);
for (int i = bin.length()-1; i >= 0; i--) {
double exponent = Math.pow(2, power);
result += ((bin.charAt(i) - 48) * (exponent));
power++;
}
System.out.print("Decimal = " + result);
}
}
//Now for the gui part >_<
---
* Synchronet * The Whitehouse BBS --- whitehouse.hulds.com --- check it out free usenet!
--- Synchronet 3.15a-Win32 NewsLink 1.92
Time Warp of the Future BBS - telnet://time.synchro.net:24