Ryan Li
Ryan Li

Reputation: 9340

Printing integers in 32-bit fixed length binary

I am using Perl to translate an integer provided by the user to binary form. For example, if the user input is "3735928559" (0xdeadbeef in hexadecimal representation), the program should output four chars respectively encoded in \xde, \xad, \xbe, \xef, instead of "deadbeef".

I don't want to use external modules, then how can I do this? Thank you.

Upvotes: 1

Views: 433

Answers (2)

cjm
cjm

Reputation: 62109

Your question isn't very clear, but I think you're looking for pack:

my $input = '3735928559';
print pack('N', $input);

Upvotes: 4

Matthew Flaschen
Matthew Flaschen

Reputation: 284927

If I understand right (you want the four bytes 0xde, 0xad, 0xbe, and 0xef), try the following:

print pack("N", $input);

Upvotes: 7

Related Questions