Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Re^3: PERL Binary Data Handling

by kcott (Canon)
on Oct 06, 2012 at 07:36 UTC ( #997594=note: print w/replies, xml ) Need Help??

in reply to Re^2: PERL Binary Data Handling
in thread PERL Binary Data Handling

G'day ashes3d,

Welcome to the monastery.

Using the data you've provided, here's a blow-by-blow account of how to achieve what I believe you're after.

#!/usr/bin/env perl use 5.010; use strict; use warnings; # Simulate the 4 bytes of input binary data (i.e. from input file) my $in_data = pack 'B32' => '01011111111100000111000011111010'; # Create new leading byte with binary value of 1 my $lead_byte = pack 'B8' => '00000001'; # Concatenate leading and input bitstrings my $concat_bitstrings = unpack('B8', $lead_byte) . unpack('B32', $in_d +ata); # Create new data with 5 (1+4) bytes my $out_data = pack 'B40' => $concat_bitstrings; # Test it worked # Converting "0101_1111_1111_0000_0111_0000_1111_1010" # and "0000_0001_0101_1111_1111_0000_0111_0000_1111_1010" # to HEX format for ease of visualising/checking my $in_hex = '5ff070fa'; my $out_hex = '01' . $in_hex; # Print expected and actual results say 'Input'; say 'EXPECT: ', $in_hex; say 'GOT: ', unpack 'H*' => $in_data; say 'Output'; say 'EXPECT: ', $out_hex; say 'GOT: ', unpack 'H*' => $out_data;


$ Input EXPECT: 5ff070fa GOT: 5ff070fa Output EXPECT: 015ff070fa GOT: 015ff070fa

I'll assume you've found the doco for pack and unpack. There's also a tutorial you may not be aware of: perlpacktut.

-- Ken

Replies are listed 'Best First'.
Re^4: PERL Binary Data Handling
by ashes3d (Initiate) on Oct 06, 2012 at 09:03 UTC
    Thank you Ken! That is what I was trying to get to. I was forgetting the "join" step. Actually, the first anonymous poster mentioned it. You guys Rock!

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://997594]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (7)
As of 2017-03-28 10:49 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (329 votes). Check out past polls.