Class: Numeric

Inherits:
Object show all
Defined in:
lib/rbkb/extends/numeric.rb

Instance Method Summary collapse

Instance Method Details

#clear_bits(c) ⇒ Object



21
22
23
# File 'lib/rbkb/extends/numeric.rb', line 21

def clear_bits(c)
  (self ^ (self & c))
end

#pack(arg) ⇒ Object

shortcut for packing a single number... wtf...



17
18
19
# File 'lib/rbkb/extends/numeric.rb', line 17

def pack(arg)
  [self].pack(arg)
end

#pad(a) ⇒ Object

calculate padding based on alignment(a)



5
6
7
8
9
# File 'lib/rbkb/extends/numeric.rb', line 5

def pad(a)
  raise "bad alignment #{a.inspect}" unless a.is_a? Numeric and a > 0

  self < 1 ? a + self : (a - 1) - (self - 1) % a
end

#printable? ⇒ Boolean

tells you whether a number is within printable range

Returns:

  • (Boolean)


12
13
14
# File 'lib/rbkb/extends/numeric.rb', line 12

def printable?
  self >= 0x20 and self <= 0x7e
end

#to_bytes(order = nil, siz = nil) ⇒ Object

"packs" a number into bytes using bit-twiddling instead of pack()

Uses to_chars under the hood. See also: to_hex

args:

siz:  pack to this size. larger numbers will wrap
order: byte order - :big or :little
                  (only :big has meaning)


55
56
57
# File 'lib/rbkb/extends/numeric.rb', line 55

def to_bytes(order = nil, siz = nil)
  to_chars(order, siz) { |c| c.chr }.join
end

#to_chars(order = nil, siz = nil) ⇒ Object

Returns an array of chars per 8-bit break-up. Accepts a block for some transformation on each byte. (used by to_bytes and to_hex under the hood)

args:

order: byte order - :big or :little
                  (only :big has meaning)
siz:  pack to this size. larger numbers will wrap


33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/rbkb/extends/numeric.rb', line 33

def to_chars(order = nil, siz = nil)
  order ||= Rbkb::DEFAULT_BYTE_ORDER
  n = self
  siz ||= size
  ret = []
  siz.times do
    c = (n % 256)
    if block_given? then (c = yield(c)) end
    ret << c
    n = (n >> 8)
  end
  (order == :big ? ret.reverse : ret)
end

#to_hex(o = nil, s = nil) ⇒ Object

Converts a number to hex string with width and endian options. "packs" a number into bytes using bit-twiddling instead of pack()

Uses to_chars under the hood. See also: to_bytes

args:

siz:  pack to this size. larger numbers will wrap
order: byte order - :big or :little
                  (only :big has meaning)


69
70
71
72
73
# File 'lib/rbkb/extends/numeric.rb', line 69

def to_hex(o = nil, s = nil)
  to_chars(o, s) do |c|
    Rbkb::HEXCHARS[c.clear_bits(0xf) >> 4] + Rbkb::HEXCHARS[c.clear_bits(0xf0)]
  end.join
end