Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: forming a word from an array of its bytes

by jcb (Parson)
on Apr 07, 2021 at 22:35 UTC ( [id://11130976] : note . print w/replies, xml ) Need Help??


in reply to forming a word from an array of its bytes

Obvious method: unroll the loop: (untested)

my @array = (1, 2, 3, 4); my $val = ($array[0]) | ($array[1]<< 8) | ($array[2]<<16) | ($array[3] +<<24); printf "%d\n", $val;

If clarity is less of a concern, try unpack/pack:

my @array = (1, 2, 3, 4); my $val = unpack 'L', pack 'C4', @array; printf "%d\n", $val;

Replies are listed 'Best First'.
Re^2: forming a word from an array of its bytes
by pidloop (Novice) on Apr 08, 2021 at 04:29 UTC
    Doh! Never thought of combining unpack and pack that way. Works great, many thanks.

      The simple way to understand that combination is that pack converts "stuff" to an octet string and unpack converts an octet string to "stuff" according to template strings. Unpacking with a different template than was used for packing reinterprets the octet string, essentially "type-punning" the data. (Type-punning is a C trick where the element of a C union object that is read is not the element that was most recently written.)

      This explanation is how I remember when to use pack and when to use unpack.