Accessing individual bits in a number

G

googler

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.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top