Dec 25
Merry Christmas!!
I love the ability that Ruby has to extend common value types and add my own personal methods. One that I use alot is a simple ‘Hexdump’ method for the String class:
#!/usr/bin/ruby
class String
def hexdump
i = 1
rr = ""
while (self.length > 16*(i-1))
a=self.slice(16*(i-1)..(16*i)-1)
rr += sprintf("%06x: %4.4x %4.4x %4.4x %4.4x %4.4x %4.4x %4.4x %4.4x ", (i-1)*16, *a.unpack("n16"))
rr += sprintf("|%s|\n", a.tr("^\040-\176","."))
i += 1
end
return rr
end
end
if __FILE__ == $0
infile = File.new(ARGV[0], "r")
ff = infile.read
infile.close
puts ff.hexdump
end
exit
The first part extends the String class, adding the ‘hexdump’ method. Calling this method on any string will return a dump of the string in hex. Its patterned after a very old BASIC program I used long ago. The bottom part of the code implements a file hexdump program:
john@Orb:~/Dev/Ruby$ ./hexdump.rb /etc/rc.local 000000: 2321 2f62 696e 2f73 6820 2d65 0a23 0a23 |#!/bin/sh -e.#.#| 000010: 2072 632e 6c6f 6361 6c0a 230a 2320 5468 | rc.local.#.# Th| 000020: 6973 2073 6372 6970 7420 6973 2065 7865 |is script is exe| 000030: 6375 7465 6420 6174 2074 6865 2065 6e64 |cuted at the end| 000040: 206f 6620 6561 6368 206d 756c 7469 7573 | of each multius| 000050: 6572 2072 756e 6c65 7665 6c2e 0a23 204d |er runlevel..# M| 000060: 616b 6520 7375 7265 2074 6861 7420 7468 |ake sure that th| 000070: 6520 7363 7269 7074 2077 696c 6c20 2265 |e script will "e| 000080: 7869 7420 3022 206f 6e20 7375 6363 6573 |xit 0" on succes| 000090: 7320 6f72 2061 6e79 206f 7468 6572 0a23 |s or any other.#| 0000a0: 2076 616c 7565 206f 6e20 6572 726f 722e | value on error.| 0000b0: 0a23 0a23 2049 6e20 6f72 6465 7220 746f |.#.# In order to| 0000c0: 2065 6e61 626c 6520 6f72 2064 6973 6162 | enable or disab| 0000d0: 6c65 2074 6869 7320 7363 7269 7074 206a |le this script j| 0000e0: 7573 7420 6368 616e 6765 2074 6865 2065 |ust change the e| 0000f0: 7865 6375 7469 6f6e 0a23 2062 6974 732e |xecution.# bits.| 000100: 0a23 0a23 2042 7920 6465 6661 756c 7420 |.#.# By default | 000110: 7468 6973 2073 6372 6970 7420 646f 6573 |this script does| 000120: 206e 6f74 6869 6e67 2e0a 0a65 7869 7420 | nothing...exit | 000130: 300a 0000 0000 0000 0000 0000 0000 0000 |0.|







December 1st, 2011 at 3:35 pm
[...] being sent, etc. Personally, I’m used to using a very common hexdump format that I’ve created Ruby methods for…but I could not find anything similar for iRules, so I wrote my [...]