Last active
October 23, 2019 17:29
-
-
Save Yeboster/2f388226e465f55030169e10385df4da to your computer and use it in GitHub Desktop.
Integer to hex code - scheme lang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(define remainder-to-hex ; val: string | |
(lambda (n) ; n: integer 0 <= n <= 16 | |
(let ((str-offset (lambda (k) (int->string (+ n k))))) | |
(cond ((< n 10) (str-offset 48)) | |
((> n 9) (str-offset 55)) | |
(else "NOTVALID") | |
) | |
) | |
) | |
) | |
(define convert-int-hex-unwrapped ; val: string | |
(lambda (n) ; n: integer | |
(let ((q (/ n 16)) (r (remainder n 16))) | |
(if (= q 0) | |
"" | |
(string-append | |
(convert-int-hex-unwrapped (floor q)) | |
(remainder-to-hex r) | |
) | |
) | |
) | |
) | |
) | |
; wrapping to cover the 0 case without messing the result | |
(define convert-int-hex ; val: string | |
(lambda (n) ; n: integer | |
(if (= n 0) | |
"0" | |
(convert-int-hex-unwrapped n) | |
) | |
) | |
) | |
(convert-int-hex 123) ; => "7B" |
Fixed 0 case with a wrap, preferred way since it doesn't add a 0 in front of the result.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fixed 0 case, using floor instead of round.