# Accessing individual bits in a number

#### Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on
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

## Re: Accessing individual bits in a number

this looks like 1 or 0

\$binary array will propagate alternate 0/1 where
\$binary[0] depends on if input decimal is even or odd

this looks like a single element asignment

-<snip>-

## Re: Accessing individual bits in a number

This gives your array without the loop:

\$bstring = sprintf "%016b",\$input_decimal;
@binary = split //,reverse(\$bstring);

The rest looks pretty efficient.
** Posted from http://www.teranews.com **

## Re: Accessing individual bits in a number

It seems you already know this:

You use &

and >>

and ^

what more do you need?

(well, ~, | and <<, of course, but I guess you know about them, too)

hp