Skip to content

Instantly share code, notes, and snippets.

@Yeboster
Last active October 23, 2019 17:29
Show Gist options
  • Save Yeboster/2f388226e465f55030169e10385df4da to your computer and use it in GitHub Desktop.
Save Yeboster/2f388226e465f55030169e10385df4da to your computer and use it in GitHub Desktop.
Integer to hex code - scheme lang
(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"
@Yeboster
Copy link
Author

Fixed 0 case, using floor instead of round.

@Yeboster
Copy link
Author

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