Accessing individual bits in a number

Discussion in 'Perl Misc' started by googler, May 19, 2008.

  1. googler

    googler Guest

    I need to find the Gray code equivalent of a given number. The number
    should be entered as an input (in decimal) and the output should be
    the Gray code equivalent (a string of 1s and 0s). For this
    computation, I need to perform XOR operations between the bits of the
    input number. Is there a way by which individual bits in a number can
    be accessed in Perl? I did it in the following way (assuming each
    number is 16 bits wide).

    --------

    $input_decimal = <STDIN>;

    ##calculate binary
    $x = $input_decimal;
    for ($i = 0; $i < 16; $i++)
    {
    $binary[$i] = $x & 0x0001;
    $x = $x >> 1;
    }

    print "binary: ";
    print reverse(@binary);

    ##calculate gray
    $gray[15] = $binary[15];
    for ($i = 14; $i >= 0; $i--)
    {
    $gray[$i] = $binary[$i+1] ^ $binary[$i];
    }

    print "\ngray: ";
    print reverse(@gray);
    print "\n";

    --------

    Basically I extracted each bit from the input number and placed them
    in an array (called @binary) and peformed XOR operations on these
    array elements. It works, but I guess there might be a better way to
    do it. Please comment. Thanks.
     
    googler, May 19, 2008
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. sarmin kho
    Replies:
    2
    Views:
    840
    A. Lloyd Flanagan
    Jun 15, 2004
  2. Miki Tebeka
    Replies:
    1
    Views:
    453
    Marcin 'Qrczak' Kowalczyk
    Jun 14, 2004
  3. benn
    Replies:
    5
    Views:
    533
    Joseph Kesselman
    Mar 20, 2008
  4. Hybr1dz
    Replies:
    6
    Views:
    2,496
    Hybr1dz
    Apr 2, 2008
  5. harijay
    Replies:
    4
    Views:
    466
    harijay
    Feb 24, 2009
Loading...

Share This Page