Results 1 to 2 of 2
  1. #1
    Chuklol is offline Member
    Join Date
    Sep 2011
    Posts
    7
    Rep Power
    0

    Default Converting a 2's complement to the proper integer

    So my question accepts an input as an 8 char string that is a 2s complement of an integer, and then prints the right integer out. I cannot use any classes that do the conversion but i can use any I/O facilities.

    Now i am still new to Java terms and not very knowledgeable of terms yet, so what does it mean that i can use any I/O facilities.

    Back to what i am thinking of doing

    I accept the string lets say, 000000C2 which is 194, (c = 12) 12 x 16^1 + 2*16(0) == 192 + 2 = 194

    I send my string to
    Java Code:
    public String toBinary (String s){
        	String ret = "";
        	while (s.length () != 0){
        		if(s.charAt (0) == '0'){
        			ret = ret + "0000";
        		}
    Which will convert 0 - F to its 4 binary part. Then returns the 32 bit binary code.
    Now if it positive i can just go through right to left if the value is 1 i add 16^i to an int, and i increases every time i loop through a value.
    If negative i have to twos complement - convert 1s to 0s, 0s to 1s and i subtract one because im going from twos complement back to its original.

  2. #2
    jing-yi is offline Member
    Join Date
    May 2011
    Posts
    35
    Rep Power
    0

    Default Re: Converting a 2's complement to the proper integer

    Try this,

    System.out.println(Integer.parseInt("000000C2",16) );

    Regards,
    Jing-yi

Similar Threads

  1. Converting an integer into a BigInteger
    By mzjazzygirl in forum New To Java
    Replies: 27
    Last Post: 09-23-2010, 06:37 PM
  2. Reading a two's complement number from a InputStream
    By TorErik86 in forum Networking
    Replies: 1
    Last Post: 09-20-2010, 02:21 PM
  3. while and proper conditions for if
    By Saletra in forum New To Java
    Replies: 11
    Last Post: 08-25-2010, 10:37 AM
  4. convert unsigned integer to signed integer in java?
    By diskhub in forum New To Java
    Replies: 6
    Last Post: 05-17-2010, 12:50 AM
  5. Replies: 24
    Last Post: 05-18-2009, 10:23 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •