Results 1 to 3 of 3
  1. #1
    sarshad is offline Member
    Join Date
    Jul 2010
    Posts
    2
    Rep Power
    0

    Exclamation Funny glitch while converting from int to 32 bit binary.....

    Hi guys,

    I'm facing a strange problem. I know an int in Java is 4 bytes or 32 bits long and is represented in the 2's complement form. As per my understanding, a value of 128 should thus be represented as: 00000000 00000000 00000000 10000000 - ie 4 bytes long. I used the following program to extract this bit by bit:

    public class IntTest {

    public static void main(String[] args)
    {

    int test = 128;
    int pr;

    for (int y = 0; y<32; y++)
    {
    pr = ((test & 0x8000) == 0) ? 0 : 1; //get value of leftmost bit
    System.out.print(pr + " ");
    test <<= 1; //shift left 1 place
    }

    }
    }

    But to my surprise, the result I get is: 00000000 10000000 00000000 00000000

    as if the int were only 2 bytes long!!!

    I've tried my best to figure out why this is happening but unless int in Java is 2bytes, which I dont think it is - I'm at a loss as to the correct answer!

    Any help would be much appreciated.

    Sarshad

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,445
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by sarshad View Post
    Java Code:
    pr = ((test & 0x8000) == 0) ? 0 : 1; //get value of leftmost bit
    0x8000 isn't the leftmost bit; use 0x80000000 instead.

    kind regards,

    Jos

  3. #3
    sarshad is offline Member
    Join Date
    Jul 2010
    Posts
    2
    Rep Power
    0

    Default Thank you!

    Thanks a ton Jos!

    That was stupid of me...... I forgot that a byte has two hex values!! :)

    Sarshad

Similar Threads

  1. Converting mp3 files to binary
    By kylefrank in forum Advanced Java
    Replies: 4
    Last Post: 06-09-2010, 08:25 PM
  2. Button Glitch
    By dunafrothint in forum AWT / Swing
    Replies: 4
    Last Post: 02-16-2010, 04:06 PM
  3. Replies: 3
    Last Post: 07-25-2009, 01:44 PM
  4. converting image to binary code n vice versa
    By nupurashi in forum Advanced Java
    Replies: 4
    Last Post: 04-01-2009, 07:27 PM
  5. Converting a text file int binary
    By sruthi_2009 in forum New To Java
    Replies: 0
    Last Post: 03-23-2009, 03:09 PM

Posting Permissions

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