Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/ansible/knx/hexdump.rb

Instance Method Summary collapse

Instance Method Details

#hexdump(sparse = false) ⇒ Object

prints out a good’ol hexdump of the data contained in the string

parameters: sparse: true / false do we want to print multiple lines with zero values?



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/ansible/knx/hexdump.rb', line 33

def hexdump(sparse = false)
   selfsize = self.size
   first = true

   print "\n index       0 1 2 3  4 5 6 7  8 9 A B  C D E F\n\n"

   lines,rest = selfsize.divmod(16)
   address = 0; i = 0    # we count them independently for future extension.

   while lines > 0
      str = self[i..i+15]
      
      # we don't print lines with all zeroes, unless it's the last line

      if str == "\0"*16     # if the 16 bytes are all zero
      
        if (!sparse) || (sparse &&  lines == 1 && rest == 0)
           str.tr!("\000-\037\177-\377",'.')
           printf( "%08x    %8s %8s %8s %8s    %s\n", 
              address, self[i..i+3].unpack('H8'), self[i+4..i+7].unpack('H8'),
              self[i+8..i+11].unpack('H8'), self[i+12..i+15].unpack('H8'), str)
        else
              print "  ....      00 .. 00 00 .. 00 00 .. 00 00 .. 00    ................\n" if first
              first = false
 end

      else  # print string which is not all zeros

        str.tr!("\000-\037\177-\377",'.')
        printf( "%08x    %8s %8s %8s %8s    %s\n", 
              address, self[i..i+3].unpack('H8'), self[i+4..i+7].unpack('H8'),
              self[i+8..i+11].unpack('H8'), self[i+12..i+15].unpack('H8'), str)
        first = true
	end
      i += 16; address += 16; lines -= 1
   end
   
   # now do the remaining bytes, which don't fit a full line..
   # yikes - this is truly ugly!  REWRITE THIS!!

   if rest > 0
      chunks2,rest2 = rest.divmod(4)     
      j = i; k = 0
      if (i < selfsize)
         printf( "%08x    ", address)
         while (i < selfsize)
              printf "%02x", self[i]
              i += 1; k += 1
              print  " " if ((i % 4) == 0)
         end
         for i in (k..15)
                print "  "
         end
         str = self[j..selfsize]
         str.tr!("\000-\037\177-\377",'.')
         print " " * (4 - chunks2+1)
         printf("  %s\n", str)
      end
   end
end