mango/host/util.fnl

35 lines
902 B
Fennel

(local byte string.char)
(fn word->byte [x]
"convert a 32 bit word into a little endian byte string"
(string.char
(-> x (band 0xff))
(-> x (rshift 8) (band 0xff))
(-> x (rshift 16) (band 0xff))
(-> x (rshift 24))))
(fn half->byte [x]
"convert a 16 bit half-word into a little endian byte string"
(string.char
(-> x (band 0xff))
(-> x (rshift 8) (band 0xff))))
(local word-max 0xffffffff)
(fn rotate-right [x n]
"Rotate *x* right as a 32 bit integer by *n* bits."
(bor (rshift x n) (band word-max (lshift x (- 32 n)))))
(fn rotate-left [x n]
"Rotate *x* right as a 32 bit integer by *n* bits."
(bor (band word-max (lshift x n)) (rshift x (- 32 n))))
(fn hex [x ?padding]
"Convert x to hexadecimal, optionally padding to ?padding characters"
(string.format (.. :% :0 (or ?padding 0) :x) x))
{: byte
: word->byte
: half->byte
: rotate-left
: rotate-right
: hex
: word-max}