my $bytes = length( $bits ); for (my $offset = 0; $offset < $bytes; $offset += 4096) { my $chunk = 4096; $chunk = $bytes - $offset if $offset + $bytes > $bytes; substr($bits, $offset, $bytes) = ~ substr($bits, $offset, $bytes); }