CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
Get each bit from a number

 



hem
User

Sep 6, 2012, 9:06 AM

Post #1 of 4 (1737 views)
Get each bit from a number Can't Post

Hello

I have a 16 bit number and I have to extract each bit from that number . Each bit has a meaning and I have to run an if loop on every bit i get.

How can i extract each bit from a number in Perl

Thanks in advance


FishMonger
Veteran / Moderator

Sep 6, 2012, 9:22 AM

Post #2 of 4 (1735 views)
Re: [hem] Get each bit from a number [In reply to] Can't Post

Use the sprintf function to convert the number to binary then use either the split or substr or unpack function to access each bit.


BillKSmith
Veteran

Sep 6, 2012, 3:39 PM

Post #3 of 4 (1714 views)
Re: [hem] Get each bit from a number [In reply to] Can't Post

I find it difficult to get all the details right using the procedure that FishMonger outlined. The data structure that you describe is a bit-vector, not a number. You may be able to exploit this by using the built-in function vec. (Refer: perldoc -f vec) to both set and read the bits.
Good Luck,
Bill


hem
User

Sep 8, 2012, 12:06 PM

Post #4 of 4 (1669 views)
Re: [BillKSmith] Get each bit from a number [In reply to] Can't Post

Hi Guys

Thanks for your help. I used your advice and did the following.

Appreciate your help and time . Thanks a ton


Code
my $firstVar = 19; 
$firstVar = unpack("B32", pack("n", $firstVar));
my $First = substr($firstVar,-1,1); #to get the last bit


 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives