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.
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.