Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-6 of 6 total  RSS 

Decimal to fraction in Ruby

// Adds a 'to_fraction' method to Float. Eg. 0.5.to_fraction => [1,2]

class Float
  def number_decimal_places
    self.to_s.length-2
  end
  
  def to_fraction
    higher = 10**self.number_decimal_places
    lower = self*higher

    gcden = greatest_common_divisor(higher, lower)

    return (lower/gcden).round, (higher/gcden).round
  end
  
private

  def greatest_common_divisor(a, b)
     while a%b != 0
       a,b = b.round,(a%b).round
     end 
     return b
  end
end

bindec.scm

// Convert list of 1s and 0s back to base ten number.

; Andrew Pennebaker
; 5 Feb 2007
; License: GPL
; URL: http://snippets.dzone.com/posts/show/3479

(define bin->dec
	(lambda (b)
		(cond
			((integer? b) b)
			((= (length b) 0) 0)
			(else
				(+
					(* (expt 2 (- (length b) 1)) (car b))
					(bin->dec (cdr b)))))))

decbin.scm

// Converts a base ten integer to a list of 1s and 0s

; Andrew Pennebaker
; 3 Feb 2007
; License: GPL
; URL: http://snippets.dzone.com/posts/show/3478

(define dec->bin
	(lambda (d)
		(cond
			((< d 1) (list 0))
			((= d 1) (list 1))
			((> d 1) (append
				(dec->bin (floor (/ d 2)))
				(list (if (= (modulo d 2) 0) 0 1)))))))

Convert a decimal value to hex in Python

// Convert a dec value to hex

hexValue = "%X" % 256
print hexValue  #100

to-octal function

    to-octal: func [
        "Converts an integer to an octal issue!."
        value [integer!] "Value to be converted"
        /width wd
        /local result pad
    ][
        pad: func [val wd] [head insert/dup val #"0" wd - length? val]
        result: copy #   ; empty issue!
        if 0 = value [return pad result any [wd 1]]
        while [0 <> value] [
            insert result value // 8
            value: round/down value / 8
        ]
        pad result any [wd 1]
    ]

from-octal

    from-octal: func [
        "Converts an octal number to a decimal value."
        octal [any-string! integer!]
        /local result len
    ][
        result: 0
        octal: form octal
        repeat i len: length? octal [
            result: add result (to integer! form octal/:i) * (8 ** (len - i))
        ]
        any [attempt [to integer! result] result]
    ]
« Newer Snippets
Older Snippets »
Showing 1-6 of 6 total  RSS