Swaps the high and low nibbles of a character.
unpack('H2',$char)=~/(.)(.)/; $swapped_char=pack('H2',"$2$1");

Cheap regex hack because I couldn't figure out how to use the shift operators effectively, and vec() didnt seem quite right...

Replies are listed 'Best First'.
Re: Nibble swap
by jmcnamara (Monsignor) on Sep 28, 2002 at 00:32 UTC

    Here is another way:     $swap = pack 'h2', unpack 'H2', $char;

    --
    John.

Re: Nibble swap
by Aristotle (Chancellor) on Oct 04, 2002 at 20:13 UTC
    Why do any string conversions here at all? my $swapped = ($_ << 4 | $_ >> 4) & 0xFF;

    Makeshifts last the longest.

      That would be great if << and >> worked on bits, but I don't think they do.
      % perl -le 'print "5" << 4' 80
      i.e. 5*2^4 == 80

      -Blake

        Doh, you're right. But
        $ perl -le 'print ord("5") << 4' 848
        Though I'm not sure we can just say my $swapped = (ord($_) << 4 | ord($_) >> 4) & 0xFF; to fix it. (Don't seem to be able to wrap my head around it right now.)

        Makeshifts last the longest.