unixhome has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks: This site is now my very favorite place on the whole internet. I do have a new question. How may I set a bit or change (10100101 to 10100111) in a particular byte. Yes, what if I have the values "a5" and what to change it to "a7"? Right, changing bit number 1 (zero-based) from 0 into 1. Thanks, RV
  • Comment on How may I set a bit or change (10100101 to 10100111)?

Replies are listed 'Best First'.
Re: How may I set a bit or change (10100101 to 10100111)?
by GrandFather (Saint) on Jun 15, 2006 at 20:35 UTC

    It depends what you actually want to achieve -

    • Set the bit: $value |= 0x02;
    • Toggle the bit: $value ^= 02;
    • Increment the bit: $value += 0b00000010;

    Note that the constants are given as hex, octal and binary for the successive samples.

    For completeness it should be noted that $value &= ~2 resets the bit.


    DWIM is Perl's answer to Gödel
Re: How may I set a bit or change (10100101 to 10100111)?
by philcrow (Priest) on Jun 15, 2006 at 20:36 UTC
    You can mask and work on bits in a manner similar to C. That is, to set a bit OR your number with a number that has the bit set. Use | for or, & and, etc.:
    my $bit_set = $old_number | 0x2;
    All of those are borrowed from C notation. If your ints are too big look at Math::BigInt, which I think is standard, but I could be wrong.

    Phil

Re: How may I set a bit or change (10100101 to 10100111)?
by TGI (Parson) on Jun 15, 2006 at 21:00 UTC
Re: How may I set a bit or change (10100101 to 10100111)?
by Joost (Canon) on Jun 15, 2006 at 20:59 UTC
      my $a6 = 0b10100101;

      is a little misleading as the hex value is actually 0xA5.

      Oring 2 with 0xA6 leaves the value unchanged by the way.


      DWIM is Perl's answer to Gödel