Int to binary

I was wondering if there is a function for turning an integer into a binary number? Thanks ( tried looking it up but all that came up was binary search and some other odd topics...)
me

int i = 1023;
    // Parse and format to binary
    i = Integer.parseInt("1111111111", 2); // 1023
    String s = Integer.toString(i, 2);     // 1111111111
    // Parse and format to octal
    i = Integer.parseInt("1777", 8);       // 1023
    s = Integer.toString(i, 8);            // 1777
    // Parse and format to decimal
    i = Integer.parseInt("1023");          // 1023
    s = Integer.toString(i);               // 1023
    // Parse and format to hexadecimal
    i = Integer.parseInt("3ff", 16);       // 1023
    s = Integer.toString(i, 16);           // 3ff
    // Parse and format to arbitrary radix <= Character.MAX_RADIX
    int radix = 32;
    i = Integer.parseInt("vv", radix);     // 1023
    s = Integer.toString(i, radix);        // vv

Similar Messages

  • How to print an int in binary form ?

    Say I have an int storing 5, can I print it out as 00000101 ?
    Thank you very much

    The simplest way to do this is:
    int i = 5;
    String s = Integer.toBinaryString(i);
    System.out.println("i is: " + s);
    For me, that outputs:
    i is: 101
    Unfortunately, that doesn't get you the padding you require. Is the padding important to you, or just the binary conversion part?

  • Int to binary converions

    Is there a command i can use for converting binary to int or is it just easier to go through it and use the & operator and the >> shift ??

    int i = Integer.parseInt("1010101", 2);
    Or you have to use the bitwise operators or try with hex values

  • Small problem - int to binary...

    Hey all, I need to create a simple java applet which converts an int into it's binary representation.
    Here is the output i need:
    Enter an int: (user enters int)
    That number in binary is:
    Thats all I need. I know it has something to do with a "wrapper class", but thats all I know. :P
    Could anyone point me in the right direction plz?

    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Integer.html#parseInt(java.lang.String,%20int)

  • Conversion int - binary

    Hello everybody,
    i want to change an integer signed value (on 32 bits) in binary format and do the reverse operation.
    So i wrote :
    String binIntStr = Integer.toBinaryString(-1610612462);
    System.out.println("Binary : "+binIntStr);
    System.out.println("Int : "+Integer.parseInt(binIntStr, 2));The conversion of the int to binary runs correctly, but the reverse operation (binary string to int) throws an NumberFormatException.
    I don't understand why the operation is well done in one way and is not allowed in the other.
    The integer value is in good format (-2147483648 < -1610612462 < 2147483647) so why can't I change the binary string returned by the method toBinaryString in an integer ?

    Integer.toBinaryString() returns a string representation of the integer argument as an unsigned integer in base 2
    from the API doc
    toBinaryString
    public static String toBinaryString(int i)Returns a string representation of the integer argument as an unsigned integer in base 2.
    The unsigned integer value is the argument plus 232 if the argument is negative; otherwise it is equal to the argument.
    This value is converted to a string of ASCII digits in binary (base 2) with no extra leading 0s. If the unsigned magnitude is zero, it is represented by a single zero character '0' ('\u0030');
    otherwise, the first character of the representation of the unsigned magnitude will not be the zero character. The characters '0' ('\u0030') and '1' ('\u0031') are used as binary digits.
    Parameters:
    i - an integer to be converted to a string.
    Returns:
    the string representation of the unsigned integer value represented by the argument in binary (base 2).so you will have to figure out out to deal with signed values yourself
    Message was edited by:
    SomeoneElse

  • How can I transfer binary data from a database to another database?

    Hi all.
    I want to transfer binary data from a MS SQL Server 2000 to anohter SQL Server 2000.
    I created JDBC(table) to JDBC(stored procedure) scenario,and
    I uploaded a JPG image file to the sender table using the java program I developed.
    The JPG data was transfered to receiver,but the transfered data was broken.
    I can't not open the file correctly.
    Can XI transfer binary data using JDBC adapter?
    The sender table structure is following.
    <b>column (data type)</b>
      id  (int 4)
      binary (binary 8000)
      flag (int 4)
    The receiver stored procedure parameter is following.
    <b>parameter (data type)</b>
       id  (smallint)
      binary (binary 8000)
      flag (smallint)
    Regards.
    Yuuki

    Hi,
    <i>Can XI transfer binary data using JDBC adapter?</i>
    Ans: Yes
    Supported JDBC Types
    http://help.sap.com/saphelp_nw04s/helpdata/en/16/9dc9ac8bc72a48b80e639abaa2e497/frameset.htm
    http://help.sap.com/saphelp_nw2004s/helpdata/en/2e/96fd3f2d14e869e10000000a155106/content.htm
    Mapping JDBC types to Java types
    http://help.sap.com/saphelp_nw04/helpdata/en/7d/79dfa72d1049bc963f4f272bb1638e/frameset.htm
    Regards,
    Prateek

  • How to read a C structure with string and int with a java server using sock

    I ve made a C agent returning some information and I want to get them with my java server. I ve settled communication with connected socket but I m only able to read strings.
    I want to know how can I read strings and int with the same stream because they are sent at the same time:
    C pgm sent structure :
    char* chaine1;
    char* chaine2;
    int nb1;
    int nb2;
    I want to read this with my java stream I know readline methode to get the first two string but after two readline how should I do to get the two int values ?
    Any idea would be a good help...
    thanks.
    Nicolas (France)

    Does the server sent the ints in little endian or big endian format?
    The class java.io.DataInputStream (with the method readInt()) can be used to read ints as binary from the stream - see if you can use it.

  • Binary in java

    is it possible to declare an int a binary number. and if so, how?
    eg.
    public static final int BINARY_1 = 1; //1
    public static final int BINARY_2 = 10; //2
    public static final int BINARY_2 = 11; //3
    public static final int BINARY_4 = 100; //4
    .....etc

    Design an applet for converting numbers between binary, hexadecimal and signed decimal with the following specifications:1.It should allow the user to enter in a number in any of the above number bases and display its equivalent in the other two bases.2.The program should have one user-interface class (i.e. the applet) and one or more other classes modelling the required objects. The user-interface class should only capture user inputs and display results. Other activities should be carried out within the objects created in the applet.3.When displaying a decimal number, it should indicate �+� sign for positive and �-� sign for negative values.
    When displaying a binary number, it should have at least one leading �0� for positive and one at least leading �1� for negative values.
    Decimal numbers should be grouped in three digits, separated by commas (e.g. 1,234,567). Binary/hexadecimal should be grouped in four bits/digits (e.g. 01,0010,1010 and 1,A97D).
    Please e-mail to me,thanks.

  • Problems with Concatenating Binary Data

    Hi
    I am experiencing a problem with the unreliable concatenation of binary data.
    I have a stored procedure that I wrote to perform cell encryption on long text fields (> 4000 characters in length). This takes the string, splits it into chunks of a set length, encrypts and concatenates the encrypted chunks into a varbinary(max) variable.
    It then stores the length of the encrypted chunk at the beginning of the data (the length of output when encrypting strings of a set length is always be the same), e.g.
    DECLARE @output VARBINARY(MAX), @length INT
    SELECT @length = LEN(@encryptedchunk1)
    SELECT @output = CONVERT(binary(8), @length) + @encryptedchunk1 + @encryptedchunk2 + @encryptedchunk3 + ...
    So far so good, and when I decrypt the data, I can read the first 8 bytes of data at beginning of the binary data to get the length of the chunk:
    -- get the length of the encrypted chunk
    SELECT @length = CONVERT(INT, CONVERT(binary(8), LEFT(@encrypteddata, 8)))
    -- then remove the first 8 bytes of data
    SELECT @encrypteddata = CONVERT(VARBINARY(MAX), RIGHT(@encrypteddata, LEN(@encrypteddata) - 8))
    <snip> code to split into chunks of length @length and decrypt
    </snip>
    This is where I am experiencing an issue. 99.4% of the time, the above code is reliable. However, 0.6% of the time this fails for one of two reasons:
    the length is stored incorrectly. The length of the encrypted chunks is usually 4052 and substituting 4052 for the returned value (4051) allows the encrypted chunks to be decrypted.
    the encrypted data sometimes starts at offset 8 instead of 9. The @length variable is correctly read at length 8 but only 7 bytes should be removed from the start, e.g.
    SELECT @length = CONVERT(INT, CONVERT(binary(8), LEFT(@encrypteddata, 8)))
    SELECT @encrypteddata = CONVERT(VARBINARY(MAX), RIGHT(@encrypteddata, LEN(@encrypteddata) - 7))
    Has anyone any ideas on why this is happening and how the process can be made more reliable?
    Julian

    Use datalength, not len. Len() is designed for character strings and will ignore trailing bytes. And count characters. Datalength does exactly what you want: it counts bytes. Look at this:
    DECLARE @b varbinary(200)
    SELECT @b = 0x4142434420202020
    SELECT @b, len(@b), datalength(@b)
    Erland Sommarskog, SQL Server MVP, [email protected]

  • How to convert decimal to binary

    example:
    source:254254254254
    target:11111110111111101111111011111110

    With the following you can convert a long type value to a binary String with leading zeros. If you would not like leading zeros you can modify it in a trivial way.
      final static char[] coeffs = new char[]{(char)0x30,(char)0x31};
    public static String toBinary(long n) {
      char[] binary = new char[64];
      for(int j=0;j<binary.length;j++) binary[j]=(char)0x30; // If leading zeros are not required, simply omit this line.
      int charPointer = binary.length-1; 
      if(n==0L) return "0";
      while (n!=0L){
          binary[charPointer--] = coeffs[(int)n&1];
          n >>>= 1;
    return new String(binary);
    }

  • 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 to binary

    I really need a bit of code that will convert an int to binary. Can anyone help me with this??

    Cheers mark, certainly not how i had planned to do
    it, was going to set up [32], store the remainder in
    it, then read it backwards.I suppose you could do that, but it strikes me as sort of reinventing the wheel... :-)
    Mark

  • Printing Binary Numbers in SP

    I am trying to print binary numbers in my output.
    Below is the expected output
    1 0x5F6AB40860296D4DB07C346FA12E25FD
    2 0x5F6AB40860296D4DB07C346FA12E25FD
    Below is the output i am getting
    -1590811137
    CREATE
    TABLE Testbinary(
    [ID] [int]
    NOT
    NULL,
    [yVolumeUnitID] [binary]
    (16)
    NOT
    NULL
    insert
    into Testbinary
    values(1,0x5F6AB40860296D4DB07C346FA12E25FD)
    insert
    into Testbinary
    values(2,0x5F6AB40860296D4DB07C346FA12E25FD)
    select
    from Testbinary
    delete Testbinary
    select yVolumeUnitID
    from dbo.MdPriceDesc
    alter
    proc vol
    as
    declare
    @ID
    int,
    @VolumeID
    binary(16),
    @out
    varchar(100)
    begin
    select @ID=ID,
    @VolumeID=yVolumeUnitID
    from Testbinary
    set
    @out = @ID+''+@VolumeID
    print
    (@out)
    end
    exec vol

    You have some implicit conversion going on. Your INT column is ADDED to your VARBINARY column by 
    @out = @ID+''+@VolumeID
    DECLARE @table TABLE (id INT, number VARBINARY(MAX))
    INSERT INTO @table (id, number) VALUES
    (1, 0x5F6AB40860296D4DB07C346FA12E25FD),
    (2, 0x5F6AB40860296D4DB07C346FA12E25FD)
    declare @vb VARBINARY(MAX), @int INT
    SELECT @vb = number, @int = id
    FROM @table
    PRINT @vb
    PRINT @int+@vb
    PRINT CAST(@int AS NVARCHAR)+''+master.sys.fn_varbintohexstr(@vb)
    Don't forget to mark helpful posts, and answers. It helps others to find relevant posts to the same question.

  • 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;

  • Changing one character in a string...how hard can it be...???

    Hey guys,
    I posted something the other day about changing a binary string to one complement. Well, now I want to change that again to the two's complement of the same number.
    The (messy) code I got so far is as follows:
    import java.util.*;
    class twosComplement {
      public static void main(String[] args) {
          Scanner reader = new Scanner(System.in);
          String binary;
          String i = "0";
          String j = "1";
          System.out.println("Enter a binary String:");
          binary = reader.nextLine();
       //   int x = 15;
       // String binary = Integer.toBinaryString(x);
       // binary = ("00000000"+binary).substring(8-binary.length());
        System.out.println("Your binary number is " +binary);
        String complement = binary.replaceAll("0","x").replaceAll("1","0").replaceAll("x","1");
        System.out.println("One's complement of your binary number is " +complement);
        int n = 0;
        int k = binary.length()-n;
        String m = charAt(k);
        if (charAt(k).equals(i)) binary.replace(charAt(k), j);
        else n++;
        System.out.println(binary);
    //    do {k++; }
    //    while (charAt(k).equals(i)) 
        private static String charAt(int k) {
            throw new UnsupportedOperationException("Not yet implemented");
        }the bit at the bottom is something netbeans kindly offered to create for me, it cut out a few syntax errors but didn't quite get the program to work.
    I'm pretty sure the root of my troubles is coming from the use of the "charAt" method, which as far as i know, would be better used with arrays, but I don't know of another way to sort this stuff...
    any help would be muchly appreciated.
    Aaron.

    ok. The following is a section from the original code (see above). I was hoping this code would take a binary string (ie, '1010101') and change the least significant bit which is a '0' to a '1'. The following section is my attempt at solving this problem, but as I run it, I encounter errors. I've been studying java for 2 months. I would like to know if anybody knows WHY this isn't working, and could offer an alternative method (as I've already stated, I think the use of the method 'charAt' is the main problem)
    int n = 0;
        int k = binary.length()-n;
        String m = charAt(k);
        if (charAt(k).equals(i)) binary.replace(charAt(k), j);
        else n++;
        }Is that better?

Maybe you are looking for

  • How to include 3 sql statements in a single procedure

    I have 3 SQL statements to create 3 tables: Table1:To get all the data from an ORIGIN table that have an expiration_dates between 02/01/2006 and 04/30/2006. This has all the customer data (customer_id, company, etc…) Table 2:Secondly I am getting all

  • Possible Bug in Process Admin, has Anyone Seen this?

    All, We are seeing errors when creating a new external resource for an SQL (Oracle) database in Process Admin. We are using the latest and greatest version of Enterprise for WLS. Resource definitions are disappearing after creation in some cases. Som

  • Merging two PDFs in Preview?

    How can I merge a page from one PDF to another, separate PDF in Preview?

  • DNG 5.4 does not work well with Olympus E-620

    I just installed the DNG converter 5.4 to use with the RAW ORF files from my new Olympus E-620.  The converted images are not the same as the jpg images or the RAW images as converted by the Olympus Master software.  They are duller in the highlights

  • Archiving Issue!!!! Need an urgent reply

    My DB size is (62 GB) but the problem create 80 to 90 archiving on daily basis & one day total archiving size of the day is 30GB.Some times archiving size goes to 49 or 50 GB. The thing I can't understand is that there is not much enough DML & DDL pe