Convert grouped hexadecimal characters to bitstring in Perl

I have 256 character strings of hexadecimal characters that represent a sequence of bit flags, and I'm trying to convert them back to bitstring so that I can control them with & , | , vec and the like. Hexadecimal strings are written in integer wide-angle groups, so a group of 8 bytes, such as "76543210" , should translate to the bitstron "\x10\x32\x54\x76" , that is, the lower 8 bits are 00001000 .

The problem is that the pack " h " format works on one input byte at a time, and not on 8, so the results from using it directly will not be in the correct order. At the moment I am doing this:

 my $bits = pack("h*", join("", map { scalar reverse $_ } unpack("(A8)*", $hex))); 

which works but feels hacked. It seems like there should be a cleaner way, but my pack -fu is not very strong. Is there a better way to do this translation?

+4
source share
3 answers
 my $hex = "7654321076543210"; # can be as long as needed my $bits = pack("V*", unpack("N*", pack("H*", $hex))); print unpack("H*", $bits); #: 1032547610325476 
+5
source

Use the hex function to turn a hexadecimal string into an internal representation of a Perl number, perform bitwise operations, and use sprintf to return it to the sixth line:

 #!/usr/bin/perl use strict; use warnings; my $hex = "76543210"; my $num = hex $hex; $num &= 0xFFFF00FF; # Turn off the third byte my $new_hex = sprintf("%08x", $num); print "It was $hex and is now $new_hex.\n"; 
0
source

Consider using the excellent Bit :: Vector .

0
source

All Articles