Skrevet av Emne: Perl - How to encode a string as hex (and decode it again)  (Lest 5005 ganger)

ATC

  • Gjest
Perl - How to encode a string as hex (and decode it again)
« på: 27. ſeptember 2008, 18:24 pm »
  • [applaud]0
  • [smite]0
  • Use the pack() and unpack() functions. But you already knew that... the problem is that those functions aren't exactly self explanatory, are they?



    ATC

    • Gjest
    [Solved] Perl - How to encode a string as hex (and decode it again)
    « Svar #1 på: 27. ſeptember 2008, 18:24 pm »
  • [applaud]0
  • [smite]0
  • 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.



    Utlogget Floyd-ATC

    • Livstidsdiktator
    • Administrator
    • Guru
    • *****
    • Innlegg: 542
    • Karma: +12/-0
      • MSN Messenger - floyd@atc.no
      • Vis profil
      • floyd.atc.no
      • E-post
    Sv: Perl - How to encode a string as hex (and decode it again)
    « Svar #2 på: 04. Mars 2014, 08:49 am »
  • [applaud]0
  • [smite]0
  • More pack/unpack fun

    # Convert IP address in quad dotted decimal format to 32bit unsigned integer
    Kode: [Velg]
    perl -MIO::Socket -e 'print unpack("N", inet_aton("127.0.0.1")) . "\n";  # = 2130706433


    # Convert 32bit unsigned integer to IP address in quad dotted decimal format
    Kode: [Velg]
    perl -MIO::Socket -e 'print inet_ntoa(pack("N", 2130706433)) . "\n";# = 127.0.0.1


    -Floyd.

    --
    Det finnes 10 typer mennesker;
    de som forstår binærtall, de som ikke gjør det, og de som forstår Grey code.