als9xd
als9xd

Reputation: 854

Pad bytes to number

I'm trying to work on seperating TCP socket messages between a server and client. The way I'm trying to do this is by starting each message with 4 bytes which contains an integer describing the size of the message. The problem is I don't know how to pad that integer with the extra bytes to make it's size 4 bytes. I am on windows.

Also the server is written in node but I think I have that side of the equation figured out.

Here is some of my code if it helps:

    $data = JSON->new->utf8->encode({test=>123});
    print $OUTPUT_SOCKET length(encode('UTF-8', $data)); # This needs to be 4 bytes
    print $OUTPUT_SOCKET $data

Upvotes: 1

Views: 83

Answers (1)

ikegami
ikegami

Reputation: 385556

sprintf "%32d",  $length  # Padded with spaces
sprintf "%032d", $length  # Padded with zeroes

If it doesn't need to be a text format, use the following:

pack 'N',  $length   # 32-bit unsigned int (4 bytes) in BE byte order.
pack 'Q>', $length   # 64-bit unsigned int (8 bytes) in BE byte order.

If you take this approach, you can combine everything:

print $SOCK pack 'N/a*', $encoder->encode($data);  # Or Q>/a*

Upvotes: 1

Related Questions