Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Perl > Perl Misc > Accessing individual bits in a number

Reply
Thread Tools

Accessing individual bits in a number

 
 
googler
Guest
Posts: n/a
 
      05-19-2008
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.
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Events on individual bits of a vector Hybr1dz VHDL 6 04-02-2008 07:06 PM
How Can Individual Bits of a Word Be defined In XML? benn XML 5 03-20-2008 01:42 PM
what about unsigned and signed 8 bits number, 16 bits, etc?? sarmin kho Python 2 06-15-2004 06:40 PM
Re: what about unsigned and signed 8 bits number, 16 bits, etc?? Miki Tebeka Python 1 06-14-2004 03:19 PM
8-Bits vs 12 or 16 bits/pixel; When does more than 8 bits count ? Al Dykes Digital Photography 3 12-29-2003 07:08 PM



Advertisments