Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11130976]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (8)
As of 2024-05-21 13:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found