Method: Rex::Text.to_hex

Defined in:
lib/rex/text.rb

.to_hex(str, prefix = "\\x", count = 1) ⇒ String

Returns the escaped hex version of the supplied string

Examples:

Rex::Text.to_hex("asdf") # => "\\x61\\x73\\x64\\x66"

Parameters:

  • count (Fixnum) (defaults to: 1)

    Number of bytes to put in each escape chunk

  • str (String)

    The string to be converted

  • prefix (String) (defaults to: "\\x")

Returns:

  • (String)

    The escaped hex version of str

Raises:

  • (::RuntimeError)


525
526
527
528
529
530
531
532
533
# File 'lib/rex/text.rb', line 525

def self.to_hex(str, prefix = "\\x", count = 1)
  raise ::RuntimeError, "unable to chunk into #{count} byte chunks" if ((str.length % count) > 0)

  # XXX: Regexp.new is used here since using /.{#{count}}/o would compile
  # the regex the first time it is used and never check again.  Since we
  # want to know how many to capture on every instance, we do it this
  # way.
  return str.unpack('H*')[0].gsub(Regexp.new(".{#{count * 2}}", nil, 'n')) { |s| prefix + s }
end