Do you have a question? Post it now! No Registration Necessary. Now with pictures!
- Posted on
- Accessing individual bits in a number
May 19, 2008, 8:07 pm
rate this thread
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>;
$x = $input_decimal;
for ($i = 0; $i < 16; $i++)
$binary[$i] = $x & 0x0001;
$x = $x >> 1;
print "binary: ";
$gray = $binary;
for ($i = 14; $i >= 0; $i--)
$gray[$i] = $binary[$i+1] ^ $binary[$i];
print "\ngray: ";
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.
- » FAQ 5.8 How can I make a filehandle local to a subroutine? How do I pass filehandles betw...
- — Previous thread in » PERL Discussions