Use pack with the Z template.

Update: An example.

johngg@aleatico:~$ perl -Mstrict -Mwarnings -E ' my $str = q{example.me}; my $length = length $str; my $padTo = 4; my $rem = $length % $padTo; my $padLen = $length + ( $rem ? $padTo - $rem : 0 ); print pack qq{Z$padLen}, $str;' | hexdump -C 00000000 65 78 61 6d 70 6c 65 2e 6d 65 00 00 |example.m +e..| 0000000c

Update 2: Don't use this, if the string is already aligned to a 32-bit boundary the Z template will overwrite the last character with a NULL is it seems to always produce a C-style NULL-terminated string.

Update 3: Removed the strike-through! The solution is to only pad with pack when necessary but it does begin to look messy.

johngg@aleatico:~$ perl -Mstrict -Mwarnings -E ' my $str = q{myexample.me}; my $length = length $str; my $padTo = 4; my $rem = $length % $padTo; print $rem ? pack( qq{Z@{ [ $length + $padTo - $rem ] }}, $str ) : $str;' | hexdump -C 00000000 6d 79 65 78 61 6d 70 6c 65 2e 6d 65 |myexample +.me| 0000000c

Cheers,

JohnGG


In reply to Re: Align string on a 32-bit boundary with padding by johngg
in thread Align string on a 32-bit boundary with padding by Lucas Rey

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.