Class: BaseConvert

Inherits:
Object
  • Object
show all
Defined in:
lib/base_convert.rb

Overview

Constant Summary collapse

DIGITS =

0..9 a..z A..Z

0.upto(255).map{|i| i.chr}.select{|c| c=~/\w/ && c=~/[^_]/}
QGRAPH =
0.upto(255).map{|i| i.chr}.select{|c| c=~/[[:graph:]]/ && c=~/[^`'"]/}
BASE =
{
  :word    => DIGITS.length,
  :qgraph    => QGRAPH.length,
  :hexadecimal => 16,
  :hex   => 16,
  :decimal => 10,
  :dec   => 10,
  :octal   => 8,
  :oct   => 8,
  :binary    => 2,
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(basefrom, baseto = nil) ⇒ BaseConvert

Returns a new instance of BaseConvert.



19
20
21
22
23
24
25
26
# File 'lib/base_convert.rb', line 19

def initialize(basefrom,baseto=nil)
  baseto = basefrom if baseto.nil?
  @basefrom   = BASE[basefrom] || basefrom
  @baseto   = BASE[baseto]   || baseto
  dl = DIGITS.length
  @from_digits  = ((basefrom == :qgraph) || (@basefrom > dl))? QGRAPH : DIGITS
  @to_digits    = ((baseto   == :qgraph) || (@baseto > dl))? QGRAPH : DIGITS
end

Instance Attribute Details

#from_digitsObject

Returns the value of attribute from_digits.



18
19
20
# File 'lib/base_convert.rb', line 18

def from_digits
  @from_digits
end

#to_digitsObject

Returns the value of attribute to_digits.



18
19
20
# File 'lib/base_convert.rb', line 18

def to_digits
  @to_digits
end

Instance Method Details

#base2dec(str) ⇒ Object

Raises:

  • (ArgumentError)


36
37
38
39
40
41
42
43
44
45
46
# File 'lib/base_convert.rb', line 36

def base2dec(str)
  str = str.upcase if @basefrom < 37
  raise ArgumentError, "base is invalid" unless @basefrom.between?(2, @from_digits.length)
  res = 0
  str.to_s.each_char do |c|
    idx = @from_digits[0,@basefrom].find_index(c)
    idx.nil? and raise ArgumentError, "invalid base-#{@basefrom} digit: #{c}"
    res = res * @basefrom + idx
  end
  res
end

#convert(str) ⇒ Object



28
29
30
31
32
33
34
# File 'lib/base_convert.rb', line 28

def convert(str)
  if str.class == String
    dec = base2dec(str)
    return (@baseto == @basefrom)? dec : dec2base(dec)
  end
  dec2base(str)
end

#dec2base(n) ⇒ Object

Raises:

  • (ArgumentError)


48
49
50
51
52
53
54
55
56
57
# File 'lib/base_convert.rb', line 48

def dec2base(n)
  return @to_digits.first if n == 0
  raise ArgumentError, "base is invalid" unless @baseto.between?(2, @to_digits.length)
  res = []
  while n > 0
    n, r = n.divmod(@baseto)
    res.unshift(@to_digits[r])
  end
  res.join("") 
end