Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: How do I test if a bit has been set in a bitstring

by Athanasius (Abbot)
on Apr 25, 2013 at 02:55 UTC ( #1030560=note: print w/ replies, xml ) Need Help??


in reply to How do I test if a bit has been set in a bitstring

Extract the flag, convert it to hex, then bitwise-AND it with the flag you want to test:

#! perl use strict; use warnings; use constant { FLAG_DELETED => 0x0001, FLAG_DRAFT => 0x0002, FLAG_SEEN => 0x0004, FLAG_RECENT => 0x0008, FLAG_FLAGGED => 0x0010, FLAG_ANSWERED => 0x0020, FLAG_SAVED => 0x0040, FLAG_MDNSENT => 0x0080, FLAG_STTPENDING => 0x0100, FLAG_FAVOURITE => 0x0200, FLAG_NOTIFY => 0x0400, FLAG_STTPRESENT => 0x0800, FLAG_STTCOMPLETE => 0x1000, }; my $filename = 'mymessage.1004'; my ($flags) = $filename =~ / \. ([0-9a-fA-F]+) $ /x; $flags = hex $flags; my $favourite = $flags & FLAG_FAVOURITE; print "\nIn file '$filename', the FAVOURITE flag is ", ($favourite ? 'SET' : 'NOT SET'), "\n";

Output:

12:53 >perl 610_SoPW.pl In file 'mymessage.1004', the FAVOURITE flag is NOT SET 12:57 >

Update: Fixed the regular expression to handle all hexadecimal digits. Thanks to jwkrahn, below.

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,


Comment on Re: How do I test if a bit has been set in a bitstring
Select or Download Code
Replies are listed 'Best First'.
Re^2: How do I test if a bit has been set in a bitstring
by jwkrahn (Monsignor) on Apr 25, 2013 at 03:40 UTC
    my ($flags) = $filename =~ / \. (\d+) $ /x;

    That won't work correctly because it doesn't match the hexadecimal digits A, B, C, D, E and F.

Re^2: How do I test if a bit has been set in a bitstring
by AnomalousMonk (Abbot) on Apr 25, 2013 at 15:35 UTC
    my ($flags) = $filename =~ / \. ([0-9a-fA-F]+) $ /x;

    [0-9a-fA-F] is also available (and, IMHO, preferable) as the  [[:xdigit:]] POSIX character class. See POSIX Character Classes in perlre for info on this and its many Unicode  \p{Property} cousins.

Re^2: How do I test if a bit has been set in a bitstring
by willk1980 (Novice) on Apr 26, 2013 at 22:05 UTC
    Thanks for the quick responses. It was using hex EXPR I was missing from my tests. Many thanks for the help, especially Athanasius and BrowserUk.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1030560]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (8)
As of 2015-07-30 23:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (273 votes), past polls