Ano-Tech Computers
Enter keyword:

Perl - How to encode a string as hex (and decode it again)
Problem:
Use the pack() and unpack() functions. But you already knew that... the problem is that those functions aren't exactly self explanatory, are they?
 
Solution:
The concept of "packing" vs. "unpacking" in Perl may seem a bit confusing because we consider clear text "unpacked" and hex "packed". When you think about it, this is ofcourse not really the case as the hex string will always be a hex string but the "clear text" can really be any binary data you can think of.

unpack("H*", "my string"); # = "6d7920737472696e67"
pack("H*", "6d7920737472696e67"); # = "my string"

By the way, don't think for a second that this can be useful for encrypting sensitive data. Hex is almost as easy to read as plaintext once you know the ASCII table.
 
Discuss this solution
Did this article solve your problem? Yes No Did not apply

We welcome anyone who is willing to contribute to this public knowledge base, contact siteadmin@atc.no if you have information you would like to share. The idea is not to replace the commercial support sites, but to publish those hard-to-find solutions you've found yourself looking for over and over again.

Show all articles