$str = 'Hello, world!'; $len = length $str; $packed_str = pack 'N', $len; $len += 4 - (($len % 4) || 4); # next multiple of 4 $packed_str .= pack "Z$len", $str; # for testing: ($test_str = $packed_str) =~ s/([^\x20-\x7E])/sprintf '\\x%02x', ord $1/ge; print "$test_str\n"; __END__