Binary To Decimal

Hi i am having trouble from converting a binary number into decimal. I found the following code from a tutorial online and would like to merge it inside the code i currently have.
This is the example i found online:
//initialize the place values
var place:Array = [32, 16, 8, 4, 2, 1];
//initialize your binary number
var binary:Array = [1, 1, 0, 0, 1, 1];
//trace it as a string
trace(binary.join(""));
//convert it to a decimal number
var decimalNumber = (place[0]*binary[0])+(place[1]*binary[1])+(place[2]*binary[2])+(place[3]*binary[3])+(place[4]*binary[4])+(place[5]*binary[5]);
//trace the result
trace(decimalNumber);
This is the code i currently have
var binaryArray:Array = new Array();
var num:Number;
var binaryString:String;
var round:Number;
var bString:String;
var bNumber:Number;
decimal_txt.addEventListener(KeyboardEvent.KEY_DOWN, checkEnterKey);
function checkEnterKey(e:KeyboardEvent):void
if(decimal_txt.text != '' && e.keyCode == Keyboard.ENTER)
num = Number(decimal_txt.text);
//trace(e.keyCode + " : " + tf.text);
bString = convertDecimalToBinary(num);
bNumber = Number(binaryString);
binary_txt.text = bString;
function getTextInput(e:KeyboardEvent):void
num = Number(decimal_txt.text);
//trace(e.keyCode + " : " + tf.text);
bString = convertDecimalToBinary(num);
bNumber = Number(binaryString);
binary_txt.text = bString;
function convertDecimalToBinary(num:Number):String
if(num == 0)
return String("");
binaryString = ''; //starts with an empty string
while(num > 0)
num /= 2;
if(Math.floor(num) == num)
binaryArray.push(0);
else
binaryArray.push(1);
trace(num);
num = Math.floor(num);
for(var i:int = binaryArray.length-1; i >= 0; i--)
binaryString += binaryArray[i];
// clear array to prepare for next input
binaryArray.pop();
while (binaryString.length<8) {
binaryString = "0"+binaryString;
//trace(binaryString);
return binaryString;
However the first code already sets a decimal value in the array and calculates it but i would like to merge it with the one i have which outputs the decimal value from an input of a binary number. How would this be possible?

what output?
all you're doing is defining n when a key is down.  you're not doing anything with n so i don't see how you expect any output.
if binary_txt is a textfield with a binary (string) and decimal_txt is a textfield that should display the decimal representation of  binary_txt.text, use:
binary_txt.addEventListener(KeyboardEvent.KEY_DOWN, checkEnterKey2);
function checkEnterKey2(e:KeyboardEvent):void{
if(binary_txt.text != '' && e.keyCode == Keyboard.ENTER){
decimal_txt.text=binaryToDecimal(binary_txt.text);
function binaryToDecimal(s:String):Number{
for(var i:int=0;i<s.length;i++){
n+=Number(s.substr(i,1))<<(s.length-1-i)
return n;

Similar Messages

  • Binary to Decimal problems

    Ok to give a background to why i am writing this and so everyone has a better understanding of exactly what it is that i want it to do it goes like this.... My girlfriend got a message from a friend that was all in ones and zeros, and no its not because something on one of the mail servers is messed up he meant for it to be that way. But through the process of converting the 8 digit binary numbers into decimal values so that the corresponding ANSI character could be found I decided that it was taking to damn long so i would just write a prog to do it for me and then i could send back an annoying long message to that guy with ease. Only there is a catch over the summer i went from hotshot for a newb to a newb without a clue, i more or less didnt write a single line of code over 4 months and now i am having problems.
    I wanted to write a program that could-
    -convert long strings of chars into all 8 digit binary code
    -as well as convert large blocks of 8 digit binary back into ANSI letter values and then ANSI characters
    -I want it to use a frame and have a relativly simple usage procedure
    Now that you know what i set out to do I can show you how far i got -
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.GradientPaint.*;
    public class BinaryToDec extends JFrame implements ActionListener
         // member variables
         JButton quit;
         JButton color;
         JButton convert;
         JLabel     label11_5, labelPassingWord;
         JTextField inputBinary, outputDecimal;
         Color      colorStore;
         String drawString;
         String bin;
         public BinaryToDec()
              drawString = "";
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setLocation(100,250);
              setTitle("Binary to Decimal");
              setSize(420,200);
              getContentPane().setBackground(Color.BLACK);
              getContentPane().setLayout(null);
              quit= new JButton("DONE");
              quit.setForeground(Color.GREEN);
              quit.setBackground(Color.BLACK);
              quit.setBounds(100,10,75,20);
              getContentPane().add(quit);
              quit.addActionListener(this);
              color= new JButton("Bkgnd Clr");
              color.setForeground(Color.GREEN);
              color.setBackground(Color.BLACK);
              color.setBounds(15,10,75,20);
              getContentPane().add(color);
              color.addActionListener(this);
              convert= new JButton("Convert to Decimal");
              convert.setForeground(Color.GREEN);
              convert.setBackground(Color.BLACK);
              convert.setBounds(185,10,75,20);
              getContentPane().add(convert);
              convert.addActionListener(this);
              label11_5 = new JLabel("Enter a Binary Number");
              label11_5.setBounds(75,60,250,20);
              label11_5.setForeground(Color.GREEN);
              getContentPane().add(label11_5);
              inputBinary = new JTextField(25);
              inputBinary.setBounds(5,40,225,20);
              inputBinary.setForeground(Color.BLACK);
              getContentPane().add(inputBinary);
              inputBinary.addActionListener(this);
              labelPassingWord = new JLabel("Your Deciaml Equivilant");
              labelPassingWord.setBounds(75,120,250,20);
              labelPassingWord.setForeground(Color.GREEN);
              getContentPane().add(labelPassingWord);
              outputDecimal = new JTextField(25);
              outputDecimal.setBounds(5,100,225,20);
              outputDecimal.setForeground(Color.BLACK);
              getContentPane().add(outputDecimal);
              outputDecimal.addActionListener(this);
              setVisible(true);
         }// end of constructor
         public void actionPerformed (ActionEvent evt)
              if(evt.getActionCommand().equals("DONE"))
                   System.out.println("Quit Caught");
                   int choice = JOptionPane.showConfirmDialog(null , "You Pressed " + evt.getActionCommand() + " are you sure?"
                        , "Close Frame",JOptionPane.YES_NO_OPTION);
                   if(choice == 0)
                        this.dispose();
                   if (evt.getSource() == color)
                        Color color = Color.lightGray;
                        color = JColorChooser.showDialog(BinaryToDec.this,"Choose a color",color);
                        getContentPane().setBackground(color);
                   if (evt.getSource() == convert)
                        bin = inputBinary.getText();
                        int strLength = bin.length();
                        int pos1=0, pos2=7;
                        String temp = "";
                        String Decimal1 = "";
                        String Decimal2 = "";
                        int binLength = 8;
                        int count = 0;
                             do
                                  temp = bin.substring(pos1,pos2);
                                  Decimal1 = Convert(temp);
                                  Decimal2 = Decimal2 + "" + Decimal1;
                                  pos1 = pos1 + binLength;
                                  pos2 = pos2 + binLength;
                                  count++;
                                  outputDecimal.setText(Decimal2);
                                  repaint();
                             }while((strLength/8) >count);
         }//end of actionPerform
         public void paint( Graphics g)
              super.paint(g);
         public String Convert(String a)
              int ctr=1, decimal=0;
              for (int i = a.length()-1; i>=0; i--)
              if(a.charAt(i)=='1')      decimal+=ctr;
              ctr*=2;
              String converted = "" + decimal;
              return converted;
         public static void main(String args[])
              System.out.println("Binary to Dec");
              BinaryToDec in = new BinaryToDec();
         }// end of main()
    }// end of class FrameExample1
    OK so other than that i decided to play with some of the paint functions i more or less stayed on task, at first i had it just convert 8 digit binary nums into decimal form using this -
              int ctr=1, decimal=0;
              for (int i = a.length()-1; i>=0; i--)
              if(a.charAt(i)=='1')      decimal+=ctr;
              ctr*=2;
    which i found in someone elses post and made some changes to, thank you someone whoever you are i hope you see this, anyways,.. then i decided i wanted it to check the length of a string and divide it by 8 assuming that it it a perfect block of 8 digit nums and then cut it into substring and go through the proccess of converting the binary to deciaml one piece at a time. I did it more or less, well it compiles right but whenever you put in more than one 8 digit binary number it ends up giving you some really strange decimal numbers and i cant seem to figure out why the hell it is doing this.??? I was hoping that some one could help me out.
    If you read this far than thanks for taking the time on my post :)

    Did you try to decode that message by hand and verified that it really is encoded the way you think it is?
    Here some code to try
    public static void decode(String fileIn, String fileOut) {
            try {
            FileReader in=new FileReader(fileIn);
            PrintWriter out=new PrintWriter(fileOut);
            char[] buffer=new char[8];
            int i;
            do {
                i=in.read(buffer, 0, 8);
                if(i==8) {
                    out.write(Integer.parseInt(new String(buffer),2));
            } while(i==8);
            in.close();
            out.close();
            } catch (Exception e) {}
        public static void encode(String fileIn, String fileOut) {
            try {
            FileReader in=new FileReader(fileIn);
            PrintWriter out=new PrintWriter(fileOut);       
            int i;
            while( (i=in.read()) >= 0 ) {
                String str=Integer.toBinaryString(i);
                for(int j=str.length(); j<8; j++)
                    out.write('0');
                out.write(str);
            in.close();
            out.close();
            } catch (Exception e) {}
        }

  • NI 9870 and binary coded decimal (BCD)

    I have a scale that outputs the weight in 4 digit ASCII form which I would like to input into a CompactRio 9072 with a NI 9870 card and convert to a binary integer. The weight appears as the 7th to 10th character on lines that are terminated by a CR. I am thinking I will need a loop that once the 10th character is read, the 4 least significant bits of the 4 characters are converted from BCD to binary and the character counter resets to 0 when a CR is read. I need a good method for converting BCD to an integer value in either labview or vhdl. The rest of the logic for this project is in vhdl, so I would not mind adding the conversion logic there, except that all the algorithms I have found require decimal division or comparison in several clock cycles.
    Solved!
    Go to Solution.

    Hello imr
    Thank you very much for getting in touch with us!
    I believe the following community example will resolve part of your issue.
    Binary String to Number
    https://decibel.ni.com/content/docs/DOC-11704
    I have also provided some further information for those unaware of what Binary Coded Decimal represents.
    What is Binary Coded Decimal (BCD)?
    http://digital.ni.com/public.nsf/allkb/59C2A05C123​008F286256CA90069A6F8
    Thank you for choosing National Instruments!
    Sincerely,
    Greg S.

  • Help converting binary to decimal.

    Hi all.
    I'm taking a course in Java programming and so far its been a great experience. I'm currently stumped on one of my assignments and I am kindly requesting some assistance.
    Basically I have to convert a binary entry into its decimal comparison.
    so for instance an entry of 1101 would output 13.
    I have the calculation formula, but my problem is finding out whether the point i'm looking at is either a 1 or a 0. I can't seem to 'strip it down' to the value.
    My current thought is something like this:
    binary = 1101;
    // problem is here
    thou = (binary % 1000) / 1000;
    hund = (thou % 100) / 100;
    tens = (hund % 10) / 10;
    ones = (tens % 1) / 1;
    // then do formular
    decimal = ones * 1 + tens * 2 + hund * 4 + thou * 8;
    I have searched but all the suggestions say to use a custom function or other obscure method. I don't know that stuff real well and we aren't even that far in the book either. All we've done so far is while, if .. else, condition statements.
    I will include the actual text for the question, in case i'm not clear. This text also includes a 'tip' which isn't helping me. (http://www.geocities.com/kaveman2000/q-4-25.pdf)
    Thanks again for any pointers.

    angeles1016 (and all),
    thanks for your great help and code snippets.
    angeles1016,
    using the code you provided i noticed that the last (single digit) was giving the wrong response in certain cases. (1000, 0111, 0001, ..) i could be off one.
    either way, i decided to fix it up and give you all the update.
    // do class, main function stuff
         if(binary/1000 == 1){
              thousands += (binary/1000);
         temp = binary % 1000;          
         if(temp/100 == 1){
              hundreds += (temp/100);
         temp = temp % 100;          
         if(temp/10 == 1){
              tens += (temp/10);
         temp = temp % 10;
         if(temp/1 == 1){
              ones += (temp/1);
         // calculate binary to decimal     
         decimal = (ones * 1) + (tens * 2) + (hundreds * 4) + (thousands * 8);
         // take result and convert to string for output
         result += "Decimal: " + decimal + "\n";
    // display in gui ?
    // end function and class stuff(note: i suppose the statements similar to "thousands += (binary/1000);" can be simplified as "thousands = 1;")

  • Help with binary to decimal, binary to hex, and hex to ascii or ascii to hex program

    I decided to do a program that will do binary to decimal, binary to hex, and hex to ascii for a project related to a java programming course, which only needs to perform features from chapters 1-6 and 8 of Tony Gaddis's book. The functions work fine as their own main programs out side of this combined effort, so can anyone help me determine why I get the following 41 errrors saying: class, interface, or enum expected as well as any other errors that may show up afterwards because I'm stumped. My flowcharts, which have to be revised after discovering that my previous function were logically incorrect after running them in their own main are attached below as the spec sheet.
    My code is as follows and I hope you don't mind the commented lines of unused code because I'm not sure where I want things and what I want at the moment:
    import java.util.Scanner;
    import java.io.*;
    import java.lang.*;
    public class BintoDectoHextoAscii
       public static void main(String[] args)throws IOException
          Scanner input = new Scanner(System.in);
          System.out.println("Enter a binary number: ");
          String binary = input.nextLine(); // store input from user
         if (binary == input.nextLine())
          //int i= Integer.parseInt(hex,2);
          //String hexString = Integer.toHexString(i);
          //System.out.println("Hexa decimal: " + hexString);
          //int finaldecimalvalue = binaryToDecimal(hexString);
          int finaldecimalvalue = binaryToDecimal(hexString);
         if (binary != input.nextLine())
          String hexInput; // The variable Bin Input declared as the datatype int to store the Binary value  
          // Create a Scanner object for keyboard input.
          //Scanner keyboard = new Scanner(System.in);
          // Get the number of binary files.
          System.out.print("Enter the Hex value: ");
          hexInput = keyboard.nextLine();
          System.out.println("Original String: "+ hexInput);
          //String hexEquivalent = asciiToHex(demoString);
          String hexEquivalent = asciiToHex(hexInput);
          //Hex value of original String
          System.out.println("Hex String: "+ hexEquivalent);
          String asciiEquivalent = hexToASCII(hexEquivalent);
          //ASCII value obtained from Hex value
          System.out.println("Ascii String: "+ asciiEquivalent);String finalhexOutput = HextoAsciiConverter(hexEquivalent);
         if (binary != input.nextLine() && hexInput != keyboard.nextLine())
             BufferedReader binInput = new BufferedReader(new InputStreamReader(System.in));
             System.out.println("Enter the Binary number:");
             String hex = binInput.readLine();
             //String finaldecimalvalue = binaryToDecimal(decimal);
             //long finalhexvalue = BinaryToHexadecimal(num);
             long finalhexvalue = BinaryToHexadecimal();
       public static String BinaryToHexadecimal(String hex)
          //public static void main(String[] args)throws IOException
             //BufferedReader bf= new BufferedReader(new InputStreamReader(System.in));
             //System.out.println("Enter the Binary number:");
             //String hex = binInput.readLine();
             long num = Long.parseLong(hex);
             long rem;
             while(num > 0)
             rem = num % 10;
             num = num / 10;
             if(rem != 0 && rem != 1)
             System.out.println("This is not a binary number.");
             System.out.println("Please try once again.");
             System.exit(0);
             int i= Integer.parseInt(hex,2);
             String hexString = Integer.toHexString(i);
             System.out.println("Hexa decimal: " + hexString);
          return num.tolong();
      //int i= Integer.parseInt(hex,2);
      //String hexString = Integer.toHexString(i);
      //System.out.println("Hexa decimal: " + hexString);
    //} // end BintoDectoHextoAsciil
       //public static String HexAsciiConverter(String hextInput)
          // Get the number of binary files.
          //System.out.print("Enter the Hex value: ");
          //hexInput = keyboard.nextLine();
          //System.out.println("Original String: "+ hexInput);
          //String hexEquivalent = asciiToHex(demoString);
          //String hexEquivalent = asciiToHex(hexInput);
          //Hex value of original String
          //System.out.println("Hex String: "+ hexEquivalent);
          //String asciiEquivalent = hexToASCII(hexEquivalent);
          //ASCII value obtained from Hex value
          //System.out.println("Ascii String: "+ asciiEquivalent);
       //} // End function  
       private static String asciiToHex(String asciiValue)
          char[] chars = asciiValue.toCharArray();
          StringBuffer hex = new StringBuffer();
          for (int i = 0; i < chars.length; i++)
             hex.append(Integer.toHexString((int) chars[i]));
          return hex.toString();
       private static String hexToASCII(String hexValue)
          StringBuilder output = new StringBuilder("");
          for (int i = 0; i < hexValue.length(); i += 2)
             String str = hexValue.substring(i, i + 2);
             output.append((char) Integer.parseInt(str, 16));
          return output.toString();
       public static String binaryToDecimal(String binary)
            //Scanner input = new Scanner(System.in);
            //System.out.println("Enter a binary number: ");
            //String binary = input.nextLine(); // store input from user
            int[] powers = new int[16]; // contains powers of 2
            int powersIndex = 0; // keep track of the index
            int decimal = 0; // will contain decimals
            boolean isCorrect = true; // flag if incorrect input
           // populate the powers array with powers of 2
            for(int i = 0; i < powers.length; i++)
                powers[i] = (int) Math.pow(2, i);
            for(int i = binary.length() - 1; i >= 0; i--)
                // if 1 add to decimal to calculate
                if(binary.charAt(i) == '1')
                    decimal = decimal + powers[powersIndex]; // calc the decimal
                else if(binary.charAt(i) != '0' & binary.charAt(i) != '1')
                    isCorrect = false; // flag the wrong input
                    break; // break from loop due to wrong input
                } // end else if
                // keeps track of which power we are on
                powersIndex++; // counts from zero up to combat the loop counting down to zero
            } // end for
            if(isCorrect) // print decimal output
                System.out.println(binary + " converted to base 10 is: " + decimal);
            else // print incorrect input message
                System.out.println("Wrong input! It is binary... 0 and 1's like.....!");
            return decimal.toint();
       } // end function
    The errors are as follows:
    ----jGRASP exec: javac BintoDectoHextoAscii.java
    BintoDectoHextoAscii.java:65: error: class, interface, or enum expected
       public static String BinaryToHexadecimal(String hex)
                     ^
    BintoDectoHextoAscii.java:73: error: class, interface, or enum expected
             long rem;
             ^
    BintoDectoHextoAscii.java:74: error: class, interface, or enum expected
             while(num > 0)
             ^
    BintoDectoHextoAscii.java:77: error: class, interface, or enum expected
             num = num / 10;
             ^
    BintoDectoHextoAscii.java:78: error: class, interface, or enum expected
             if(rem != 0 && rem != 1)
             ^
    BintoDectoHextoAscii.java:81: error: class, interface, or enum expected
             System.out.println("Please try once again.");
             ^
    BintoDectoHextoAscii.java:83: error: class, interface, or enum expected
             System.exit(0);
             ^
    BintoDectoHextoAscii.java:84: error: class, interface, or enum expected
             ^
    BintoDectoHextoAscii.java:87: error: class, interface, or enum expected
             String hexString = Integer.toHexString(i);
             ^
    BintoDectoHextoAscii.java:88: error: class, interface, or enum expected
             System.out.println("Hexa decimal: " + hexString);
             ^
    BintoDectoHextoAscii.java:90: error: class, interface, or enum expected
          return num.tolong();
          ^
    BintoDectoHextoAscii.java:91: error: class, interface, or enum expected
       ^
    BintoDectoHextoAscii.java:124: error: class, interface, or enum expected
          StringBuffer hex = new StringBuffer();
          ^
    BintoDectoHextoAscii.java:125: error: class, interface, or enum expected
          for (int i = 0; i < chars.length; i++)
          ^
    BintoDectoHextoAscii.java:125: error: class, interface, or enum expected
          for (int i = 0; i < chars.length; i++)
                          ^
    BintoDectoHextoAscii.java:125: error: class, interface, or enum expected
          for (int i = 0; i < chars.length; i++)
                                            ^
    BintoDectoHextoAscii.java:128: error: class, interface, or enum expected
          ^
    BintoDectoHextoAscii.java:130: error: class, interface, or enum expected
       ^
    BintoDectoHextoAscii.java:135: error: class, interface, or enum expected
          for (int i = 0; i < hexValue.length(); i += 2)
          ^
    BintoDectoHextoAscii.java:135: error: class, interface, or enum expected
          for (int i = 0; i < hexValue.length(); i += 2)
                          ^
    BintoDectoHextoAscii.java:135: error: class, interface, or enum expected
          for (int i = 0; i < hexValue.length(); i += 2)
                                                 ^
    BintoDectoHextoAscii.java:138: error: class, interface, or enum expected
             output.append((char) Integer.parseInt(str, 16));
             ^
    BintoDectoHextoAscii.java:139: error: class, interface, or enum expected
          ^
    BintoDectoHextoAscii.java:141: error: class, interface, or enum expected
       ^
    BintoDectoHextoAscii.java:144: error: class, interface, or enum expected
       public static String binaryToDecimal(String binary)
                     ^
    BintoDectoHextoAscii.java:150: error: class, interface, or enum expected
            int powersIndex = 0; // keep track of the index
            ^
    BintoDectoHextoAscii.java:151: error: class, interface, or enum expected
            int decimal = 0; // will contain decimals
            ^
    BintoDectoHextoAscii.java:152: error: class, interface, or enum expected
            boolean isCorrect = true; // flag if incorrect input
            ^
    BintoDectoHextoAscii.java:155: error: class, interface, or enum expected
            for(int i = 0; i < powers.length; i++)
            ^
    BintoDectoHextoAscii.java:155: error: class, interface, or enum expected
            for(int i = 0; i < powers.length; i++)
                           ^
    BintoDectoHextoAscii.java:155: error: class, interface, or enum expected
            for(int i = 0; i < powers.length; i++)
                                              ^
    BintoDectoHextoAscii.java:159: error: class, interface, or enum expected
            for(int i = binary.length() - 1; i >= 0; i--)
            ^
    BintoDectoHextoAscii.java:159: error: class, interface, or enum expected
            for(int i = binary.length() - 1; i >= 0; i--)
                                             ^
    BintoDectoHextoAscii.java:159: error: class, interface, or enum expected
            for(int i = binary.length() - 1; i >= 0; i--)
                                                     ^
    BintoDectoHextoAscii.java:166: error: class, interface, or enum expected
                else if(binary.charAt(i) != '0' & binary.charAt(i) != '1')
                ^
    BintoDectoHextoAscii.java:169: error: class, interface, or enum expected
                    break; // break from loop due to wrong input
                    ^
    BintoDectoHextoAscii.java:170: error: class, interface, or enum expected
                } // end else if
                ^
    BintoDectoHextoAscii.java:174: error: class, interface, or enum expected
            } // end for
            ^
    BintoDectoHextoAscii.java:180: error: class, interface, or enum expected
            else // print incorrect input message
            ^
    BintoDectoHextoAscii.java:185: error: class, interface, or enum expected
            return decimal.toint();
            ^
    BintoDectoHextoAscii.java:186: error: class, interface, or enum expected
       } // end function
       ^
    41 errors
    ----jGRASP wedge2: exit code for process is 1.
    ----jGRASP: operation complete.

    so can anyone help me determine why I get the following 41 errrors saying: class, interface, or enum expected as well as any other errors that may show up afterwards because I'm stumped.
    Yes - YOU CAN!
    My code is as follows and I hope you don't mind the commented lines of unused code because I'm not sure where I want things and what I want at the moment:
    Excellent! Commenting out code is EXACTLY how you troubleshoot problems like yours.
    Comment out sections of code until the problem goes away. Then start adding back ONE SECTION of code at a time until the problem occurs. When it does you have just FOUND the problem.
    If you do that you wind up with code that looks like this:
    import java.util.Scanner;
    import java.io.*;
    import java.lang.*;
    public class BintoDectoHextoAscii  {
          public static void main(String[] args)throws IOException      {
             Scanner input = new Scanner(System.in);
             System.out.println("Enter a binary number: ");
             String binary = input.nextLine(); // store input from user
                  public static String BinaryToHexadecimal(String hex)     {     } // end function        
    Notice ANYTHING UNUSUAL?
    You have a complete CLASS definition followed by a method definition.
    Methods have to be INSIDE the class - you can NOT define methods on their own.
    Write modular code.
    Write EMPTY methods - just the method signature and maybe a RETURN NULL if you need to return something.
    Then add calls to those empty methods.
    When everything compiles and runs find you can start adding code to the methods ONE METHOD AT A TIME.
    Test compile and run after you add the code for each method.

  • Conversion from Binary to decimal - Need help

    Hi guys,
    I am new here and learnt some very basic Java before. I have a program that is in C++(to convert a binary number to decimal) that I found in the internet that interest me a lot. I am thinking whether this can be re-write in Java. I have tried to searh for solution but to no avail. I am wondering whether you guys can suggest a solution to this. Below are the source code in C++ :
    #include <iostream.h>
    #include <stdlib.h>
    int main()
    // part 1 : declaration
    int Bin, Dec, TempBin;
    int div;
    char valid, again;
    do {
    // part 2 : Repeat asking the value of the binary number
    Bin = TempBin = 0;
    do {
    cout << "Please input a binary number (1 to 10 bits) : ";
    cin >> Bin;
    TempBin = Bin;
    do {
    if ((TempBin % 10)==0 || (TempBin % 10)==1) // Note (1)
    valid='Y';
    else {
    cout << "Invalid pattern! use 0's and 1's only\n\n";
    valid='N';
    break;
    TempBin = (TempBin/10);
    } while (TempBin>0);
    } while (valid=='N');
    // part 3 : Convertion
    div = 1;
    Dec = 0;
    TempBin = Bin;
    do {
    Dec += (TempBin % 10)*div; // Note (2)
    div *= 2;
    TempBin = (TempBin/10);
    } while (TempBin>0);
    cout << "\nThe binary pattern " << Bin << " is equal to "
    << Dec << " in decimal pattern.\n" << endl;
    // part 4 : try another number ?
    cout << "\aTry another number (Y/N) : ";
    cin >> again;
    cout << "\n";
    } while (again=='Y' || again=='y');
    cout << "\n" << endl;
    system("PAUSE");
    return 0;
    Appreciate your help. Thank you.
    CK

    So for Java, in your example, it takes a Java
    String like "1001" and converts it to an int whose
    value is one thousand and one. Can suggest a code for
    this that takes user input str and convert to bin int.
    I read books and noticed they are various ways to do
    that. I am quite confused actually. It is like there
    is no fix way to do that, unlike C++ which is more
    easier to understand(in my opinion). Probably, because
    I knew C better than Java.
    The 'standard' way to take a String and convert it to an int...
    int TempBin=Integer.parseInt(your_string);
    You seem to be saying that you do not want to use the standard method, so you should not complain that there is no standard method. Here's some code that re-uses most of your modulo 10.
    import java.io.*;
    public class Test {
         public static void main(String []args) throws IOException {
              BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
              String result=null;
              while(true) {
                   String input=bf.readLine().trim();
                   try {
                        long v=Long.parseLong(input);
                        result=toBin(v);
                        System.out.println(result);
                   } catch(NumberFormatException e) {
                             System.out.println("Only enter 1 or 0, nothing else!");
                   System.out.println();
           public static String toBin(long btemp) {
              long temp=btemp;
              do {
                   if ((temp % 10)!=0 && (temp % 10)!=1) {
                        System.out.println("Invalid pattern! use 0's and 1's only\n\n");
                        return null;
                   temp = (temp/10);
              } while (temp>0);
              // part 3 : Convertion
              int div = 1;
              int Dec = 0;
              long TempBin = btemp;
              do {
                   Dec += (TempBin % 10)*div; // Note (2)
                   div *= 2;
                   TempBin = (TempBin/10);
              } while (TempBin>0);
              return ""+Dec;

  • Required code to convert binary to decimal

    i need the programming logic to convert a binary number into its decimal equivalent. the program should also detect a non binary number.

    public class EnterBinary{
       public static void main (String []args){
       int binCheck=0;
       String bins="";
       try {
          bins=args[0];
       catch (Exception e){
          System.out.print("No user input, program will terminate");
          System.exit(0);
       for(int i=0; i<bins.length(); i++)
          if((bins.charAt(i)=='1')||(bins.charAt(i)=='0')) binCheck++;
       if(binCheck==bins.length() ) {
          int j=1;
          binCheck=0;
          for(int i=0; i<bins.length()-1; i++) j *=2;
          for(int i=0; i<bins.length(); i++){
             if(bins.charAt(i)=='1') binCheck += j;
             j /=2;
       System.out.print("The binay number "+bins+" in decimal is "+binCheck);
       else System.out.print("Invalid binary input, program will terminate");
    }

  • Program to convert binary to decimal number?

    I only know how to do a program that converts only 4 numbers, but it to convert any amount of digits the number enters, I think you need to use a loop or something, but I'm not sure how. Could someone please help me? This is my code so far:
    import javax.swing.JOptionPane;
    public class bintodec {
         public static void main (String[] args) {
              String input;
              int number,digit1,digit2,digit3,digit4,result;
              input = JOptionPane.showInputDialog ("Enter a binary number.");
              number = Integer.parseInt(input);
              digit1 = ((number % 10000) - (number % 10000 % 1000)) / 1000;
              digit2 = ((number % 1000) - (number % 1000 % 100)) / 100;
              digit3 = ((number % 100) - (number % 100 % 10)) / 10;
              digit4 = (number % 10);
              result = (digit1 * 8) + (digit2 * 4) + (digit3 * 2) + (digit4 * 1);
              System.out.println ( "Binary number: " + input + "\nConverted Decimal Number: " + result);
              System.exit( 0 );
         } // main
    } // bintodecany help is super-appreciated.

    I am not sure if this will help you. Check it out, run it and let me know if it helped.
    import java.util.*;
       public class BitwiseTest1 {
           public static void main(String[] args){
            System.out.println("Enter a integer number:");
            Scanner keyboard = new Scanner(System.in);
            int n1 = keyboard.nextInt();
            System.out.println( "n1 as binary " +
                   Integer.toBinaryString( n1 ));
            System.out.println( "NOT n1 =     " +
                   Integer.toBinaryString( ~n1 ));
            System.out.println("Enter another integer number:");
            int n2 = keyboard.nextInt();
            System.out.println( "n2 as binary " +
                   Integer.toBinaryString( n2 ));
             System.out.println( "NOT n2 =     " +
                   Integer.toBinaryString( ~n2 ));
    }

  • Convert binary to decimal

    hi, i was wondering what's the code to convert binary numbers to decimal numbers?

    import java.io.*;
    class convertBinarytoDecimal{
         public static void main (String args[])
         throws Exception {
              System.out.println("Enter the Binary Number");
              BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
              String str = br.readLine().trim();
              int [] myArray = new int [str.length()];
              for(int i=0;i<myArray.length;i++){
                   myArray[i] = Integer.parseInt(str.charAt(i)+"");
              convertBinarytoDecimal(myArray);
         static void convertBinarytoDecimal(int [] myArray){
              int decimal = 0;
              for (int i =0;i<myArray.length;i++){
                   decimal += myArray[i] * Math.pow(2,myArray.length-(i+1));
              System.out.println(decimal);
    }

  • Vbs binary to decimal converter

    I tried to use the following converter but it doesn`t work. Diadem says ')' expected in line 1. What is wrong with this code?
    Option Explicit 'Erzwingt die explizite Deklaration aller Variablen in einem Script.
    Public Function BinaryToDecimal(Binary As String) As Long
    Dim n As Long
    Dim s As Integer
    For s = 1 To Len(Binary)
    n = n + (Mid(Binary, Len(Binary) - s + 1, 1) * (2 ^ _
    (s - 1)))
    Next s
    BinaryToDecimal = n
    End Function
    Public Function DecimalToBinary(DecimalNum As Long) As _
    String
    Dim tmp As String
    Dim n As Long
    n = DecimalNum
    tmp = Trim(Str(n Mod 2))
    n = n \ 2
    Do While n <> 0
    tmp = Trim(Str(n Mod 2)) & tmp
    n = n \ 2
    Loop
    DecimalToBinary = tmp
    End Function
    Thanks in advance!

    Thanks for your solutions! I came a big step further through that. 
    Now I´m nearly at the solution. I wrote following programm. 
    The first part reads in special parts of a file from my pc into an array.
    The second part converts the binary parts into hex-values. (here only meinArray(0), but I am going to insert a loop)
    The third part converts the hex-values in 2`s complement into signed decimal values
    The problem is only how to give the values from the second part into the third part. It doesn´t work with the following solution:
    'first part
    Dim fso, zeile, Textdatei, Zeichen1, Zeichen2, meinArray(128), i, txt
    ' Zugriff auf das Dateisysten
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set Textdatei = fso.OpenTextFile("C:\Users\Christoph\Desktop\Projekt\11061543.003",1)
    Textdatei.Skip(40960)
    do
    Zeichen1 = Textdatei.Read(1)
    Zeichen2 = Textdatei.Read(1)
    meinArray(i)= Zeichen2 & Zeichen1
    i=i+1
    loop while i<128
    For i = LBound(meinArray) To UBound(meinArray)
    txt = txt & meinArray(i) & vbCrLf
    Next
    MsgBox txt
    'second part
    Function StrToHex(Values) ' useful for debugging!
    Dim j, k, TempVal, HexVals
    IF NOT IsArray(Values) THEN
    TempVal = Values
    ReDim Values(0)
    Values(0) = TempVal
    END IF ' the Values input is a Scaler-- map to a 1 element Array
    ReDim HexVals(UBound(Values))
    FOR j = 0 TO UBound(Values)
    HexVals(j) = ""
    FOR k = 0 TO Len(Values(j))-1
    HexVals(j) = HexVals(j) & Right("0" & Hex(Asc(Mid(Values(j), k+1, 1))), 2)
    NEXT ' k
    NEXT ' j
    IF NOT IsEmpty(TempVal) THEN
    TempVal = HexVals(0)
    HexVals = TempVal
    END IF ' the Values input was a Scaler-- return a Scaler
    StrToHex = HexVals ' returns a Variant array of [Hex][Codes][in][each][Value()]
    End Function ' StrToHex()
    StrToHex(meinArray(0))
    'third part
    Function TwoComplement8Bits(StrToHex)
    TwoComplement8Bits=CInt(StrToHex)
    If TwoComplement8Bits>127 Then
    TwoComplement8Bits=-1*((Not (TwoComplement8Bits Or &hff00))+1)
    End If
    End Function
    MsgBox TwoComplement8Bits(StrToHex)

  • Java binary to decimal?

    how do i convert a binary number to a decimal number using Jbuttons and Jlabel for the output? the binary number should be entered into a Jtextfield
    thank you

    rpgangsta wrote:
    how do i convert a binary number to a decimal number using Jbuttons and Jlabel for the output? the binary number should be entered into a Jtextfield
    thank youThe user sees a text. You read that text, convert it into an internal representation, manipulate it, and then show the result to the user again as a text.
    You have: String (read from user) -> internal data -> (manipulation of data) - > internal data - > String (shown to user).

  • Binary to decimal IP address

    Hello all,
    I have an IP address in binary format in an array
    11000000101010000110010000100010
    and I want to transform it into decimal format : 192.168.100.32.
    How can I implement this in java?
    Thanks!

    denisa wrote:
    Hello all,
    I have an IP address in binary format in an array
    11000000101010000110010000100010
    and I want to transform it into decimal format : 192.168.100.32.
    ...That's 192.168.100.34, by the way...

  • Binary to Decimal convert in reverse manner.

    Dear all,
    I have a binary data set which I want to convert using negative powers of two. For example I have a binary data
    11101100100000000000000
    which I want to convert in decimal using method below ( negative powers of two).
    (1 * 2^-1) + (1 * 2^-2) + (1 * 2^-3) + (0 * 2^-4) + ... + (0 * 2^-23).
    I have been successful till the part or reversing the whole data set but couldn't figure out the rest. Help is sorely needed. 
    Regards.
    Solved!
    Go to Solution.

    GerdW wrote:
    Edit: I added one possible "hard way bit by bit" solution as well..
    The hard way can be made quite a bit less hard, e.g. as follows.
    It is probably pretty fast (not tested, though).
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    ReverseBinaryToDecimal.png ‏16 KB

  • Binary to decimal, including negatives

    HI i have been searching through the forums but have been unable to find how to do this.
    I am using a 12bit word and need to convert it to decimal. I have tried using the Integer.parseInt(b, 2) method, however i cannot seam to make this work for negative numbers. I am using the two's compliment method to store negative numbers, for example -3 becomes 111111111100.
    Thanks for any help that you can give me!
    Alex

    The reason i'm using a 12 bit word is that the program is a simulator for the first minicomputer the DEC PDP-8. What i have to make you see is a machine code simulator, that reads in decimal values from a text file then converts these to binary and uses them as machine code.
    There seams to be an awefull lot of decimal to binary and visa versa conversion in this as when i perform a simple add the easiest way i have found is to convert both numbers to dec then add then convert back to binary.
    Thanks for all the help your giving me i still havn't managed to make it work yet though!
    Alex

  • Checking and Converting binary, octal, decimal, and hex

    Hi,
    I have a classroom project which will need to validate that data entered in a text is of a certain type with a keyListener, and then convert that value to the other 3 types.
    I know character.isDigit will handle the decimal case, and that I can then use Integer.otString methods to convert to binary, octal, and hex, but what about the other cases?
    Thanks

    OK, this isn't working. If I've already established
    that the string entered into, for example, the
    integer-only textfield is a valid integer, I should be
    able to simply use integer.parseint(s, 2) to convert
    it into binary, right?Not exactly. You should be able to use Integer.parseInt(s, 2) to return the result of converting it from binary representation. You appear to think that this affects whatever "s" refers to, which is not the case. Note also, that method returns an int which is the decimal value in question.
    When you are thinking of int variables, be careful not to think of them as "decimal" or "binary". They are neither. They are just numbers. "Decimal" and "binary" are text representations of numbers, so those concepts can only be applied to strings.
    Integer.parseInt(s, 2);
    txtBin.setText(s);So here you want to assume that the input is a string that represents a number in decimal, and you want to find the string that represents the number in binary. Like this:// convert string in decimal representation to number
    int dec = Integer.parseInt(s);
    // convert int to binary representation as string:
    String binary = Integer.toBinaryString(dec);
    // write that to the text field
    txtBin.setText(binary);You could use a one-liner to do that, but you'll need the "dec" variable to set the other text boxes.
    Rembering why I hate OO...All of what I said there is true in just about all computer languages, OO or otherwise.
    PC&#178;

Maybe you are looking for

  • Exclamation point but songs play one at a time?

    I wish I could say that after all these years I am smart enough to navigate iTunes... My setup is as follows:  iTunes library is located on a Mac Mini, a couple of Macbooks on the network use iTunes and point to this library. Almost every song in my

  • Vector in java 5

    How to use the new vector<E> class. We need to add all java types in vector.

  • JNI communiction using a Java and a C++ Thread

    Hi, My purpose is to run a Java and a C++ thread parallel. The C++ thread receives events from a hardware. Getting an event it should put this (for testing it is just a String ) to a Java method (there the events will be collected in a vector). The J

  • What is temporal join  in infoset

    what is temporal join  in infoset?

  • Resizing graphics - and jagged edges

    I have a lot of graphics that have been delivered to me 1920 x 1280. When I resize them in FCP 5.1.4., the edges are very jagged. BUT, when I bring those same graphics into After Effects and resize them and bring them into Final Cut, the edges are cl