Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re^2: Align string on a 32-bit boundary with padding

by NERDVANA (Deacon)
on Aug 20, 2022 at 14:35 UTC ( [id://11146261]=note: print w/replies, xml ) Need Help??


in reply to Re: Align string on a 32-bit boundary with padding
in thread Align string on a 32-bit boundary with padding

There's really no need for pack when you can just add  ("\0" x $n) to the original string.

Replies are listed 'Best First'.
Re^3: Align string on a 32-bit boundary with padding
by AnomalousMonk (Archbishop) on Aug 20, 2022 at 19:57 UTC
    ... add ("\0" x $n) to the original string.

    Shouldn't that be ("\0" x ($n-1)) if $n is the boundary width in bytes?

    Win8 Strawberry 5.8.9.5 (32) Sat 08/20/2022 15:46:20 C:\@Work\Perl\monks >perl use strict; use warnings; use bytes; use Data::Dump qw(pp); use constant BYTE_BOUND => 4; use constant PAD => "\0" x (BYTE_BOUND-1); my $s = 'TheRainInSpainFalls'; while (length $s) { my $p = $s . PAD; $p = bytes::substr $p, 0, bytes::length($p) - bytes::length($p)%BY +TE_BOUND; printf "%4s - %-28s \n", bytes::length($p), pp($p); chop $s; } ^Z 20 - "TheRainInSpainFalls\0" 20 - "TheRainInSpainFall\0\0" 20 - "TheRainInSpainFal\0\0\0" 16 - "TheRainInSpainFa" 16 - "TheRainInSpainF\0" 16 - "TheRainInSpain\0\0" 16 - "TheRainInSpai\0\0\0" 12 - "TheRainInSpa" 12 - "TheRainInSp\0" 12 - "TheRainInS\0\0" 12 - "TheRainIn\0\0\0" 8 - "TheRainI" 8 - "TheRain\0" 8 - "TheRai\0\0" 8 - "TheRa\0\0\0" 4 - "TheR" 4 - "The\0" 4 - "Th\0\0" 4 - "T\0\0\0"


    Give a man a fish:  <%-{-{-{-<

      $n was whatever you are adding to the string from your other math. My only point was that appending a short string of "\0" is faster and less to look at than using unpack to split the string on every byte and then re-join them.

        Fair enough.


        Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2024-03-29 15:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found