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

Hello, I have a 36 bit Address string and I need to do the following in Perl: If the 31st bit of the Address = 1, make it '0'. So if the Address = 0x000000019, make it Address_new = 0x9 Any idea what is the best way to do this in Perl? I tried changing the address from decimal to binary and concatenating with zero and then in a loop, search for the 31st bit and make it zero. Somehow it is not working properly.

Replies are listed 'Best First'.
Re: Changing a bit in a string
by moritz (Cardinal) on Apr 07, 2011 at 11:53 UTC
Re: Changing a bit in a string
by salva (Canon) on Apr 07, 2011 at 12:11 UTC
    s/([13579bdf].)$/sprintf("%02x", hex($1) - 16)/ei;

    Though, in practice, instead of using this obscure regexp, I would probably convert it into a bit vector and use vec to change the bit at position 31.

Re: Changing a bit in a string
by syphilis (Archbishop) on Apr 07, 2011 at 14:09 UTC
    Looks to me that the following does the job:
    $address -= 16 if $address & 16;
    Cheers,
    Rob