| 1 |
;; |
| 2 |
;; numconv.scm |
| 3 |
;; (c) Norbert Preining 1997 |
| 4 |
;; This file is part of the otibet-package. |
| 5 |
;; |
| 6 |
;; Converting hex <-> dec <-> oct values |
| 7 |
;; hex, oct are STRINGS!!! |
| 8 |
;; dec is INTEGER |
| 9 |
;; |
| 10 |
;; Provides: |
| 11 |
;; (dec->hex INTEGER) -> STRING |
| 12 |
;; (dec->oct INTEGER) -> STRING |
| 13 |
;; (hex->dec STRING) -> INTEGER |
| 14 |
;; (oct->dec STRING) -> INTEGER |
| 15 |
;; (oct->hex STRING) -> STRING |
| 16 |
;; (hex->oct STRING) -> STRING |
| 17 |
;; |
| 18 |
;; Comment: Not very effective, just a quick hack. |
| 19 |
;; |
| 20 |
(define (number->hex-digit n) |
| 21 |
(if (and (integer? n) (> n -1) (< n 16)) |
| 22 |
(if (< n 10) |
| 23 |
(string (integer->char (+ n (char->integer #\0)))) |
| 24 |
(string (integer->char (+ n (char->integer #\A) -10)))) |
| 25 |
(error 'number->hex-digit |
| 26 |
"Argument ~a not a integer or out of range!" n))) |
| 27 |
|
| 28 |
(define (hex-digit->number h) |
| 29 |
(let ((n (- (char->integer (string-ref h 0)) 65))) |
| 30 |
(if (< n 0) |
| 31 |
(+ n 17) |
| 32 |
(+ n 10)))) |
| 33 |
|
| 34 |
(define (number->oct-digit n) |
| 35 |
(if (and (integer? n) (> n -1) (< n 8)) |
| 36 |
(string (integer->char (+ n (char->integer #\0)))) |
| 37 |
(error 'number->oct-digit |
| 38 |
"Argument ~a not a integer or out of range!" n))) |
| 39 |
|
| 40 |
(define (oct-digit->number h) |
| 41 |
(- (char->integer (string-ref h 0)) (char->integer #\0))) |
| 42 |
|
| 43 |
(define (dec->hex n) |
| 44 |
(if (= n 0) |
| 45 |
"" |
| 46 |
(letrec ((rem (modulo n 16)) |
| 47 |
(rval (/ (- n rem) 16))) |
| 48 |
(string-append (dec->hex rval) (number->hex-digit rem))))) |
| 49 |
|
| 50 |
(define (hex-list->dec x) |
| 51 |
(if (= (length x) 0) |
| 52 |
0 |
| 53 |
(+ (* 16 (hex-list->dec (cdr x))) |
| 54 |
(hex-digit->number (string (car x)))))) |
| 55 |
|
| 56 |
(define (hex->dec x) |
| 57 |
(hex-list->dec (reverse (string->list x)))) |
| 58 |
|
| 59 |
(define (dec->oct n) |
| 60 |
(if (= n 0) |
| 61 |
"" |
| 62 |
(letrec ((rem (modulo n 8)) |
| 63 |
(rval (/ (- n rem) 8))) |
| 64 |
(string-append (dec->oct rval) (number->oct-digit rem))))) |
| 65 |
|
| 66 |
(define (oct-list->dec x) |
| 67 |
(if (= (length x) 0) |
| 68 |
0 |
| 69 |
(+ (* 8 (oct-list->dec (cdr x))) |
| 70 |
(oct-digit->number (string (car x)))))) |
| 71 |
|
| 72 |
(define (oct->dec x) |
| 73 |
(oct-list->dec (reverse (string->list x)))) |
| 74 |
|
| 75 |
(define (hex->oct x) |
| 76 |
(dec->oct (hex->dec x))) |
| 77 |
|
| 78 |
(define (oct->hex x) |
| 79 |
(dec->hex (oct->dec x))) |