The previous answers didn't work for us, so here are two quick functions for converting an integer into multiple different bases, including hexadecimal:
@function decimal-to-base($decimal, $to_base, $chars: '0123456789abcdefghijklmnopqrstuvwxyz')
@if type-of($decimal) != 'number'
@error '$decimal must be an integer.'
@if type-of($to_base) != 'number'
@error '$to-base must be an integer.'
@if type-of($chars) != 'string'
@error '$chars must be a string.'
@if $to_base < 2
@error '$to-base must be larger than 1.'
@if $to_base > str-length($chars)
@error 'Length of $chars must be equal or larger than $to-base.'
@return _decimal-to-base($decimal, $to_base, $chars)
@function _decimal-to-base($decimal, $to_base, $chars, $_accum: '')
@if $decimal <= 0
@return if($_accum != '', $_accum, '0')
$remainder: $decimal % $to_base
$char: str-slice($chars, $remainder + 1, $remainder + 1)
$remaining_decimal: ($decimal - $remainder) / $to_base
@return _decimal-to-base($remaining_decimal, $to_base, $chars, $char + $_accum)
If you don't care about error handling, you can skip the long first function (which really only validates the arguments and sets the default characters) and just copy the second function.
Also, note that this is written in SASS, not SCSS. For SCSS support, you'll want to sprinkle in some curly brackets and semicolons.
Examples:
Decimal to Hexadecimal:
decimal-to-base(15731618, 16) // "f00ba2".
Decimal to binary:
decimal-to-base(34, 2) // "100010".
Timestamp to query string:
decimal-to-base(1547598870, 2) // "pleb0y".
Definitely not Morse code:
decimal-to-base(34, 2, '-.') // "-...-.".
Over-engineered integer to string:
decimal-to-base(123456, 10) // "123456".
Known caveats: (because this is a dirty implementation)
- Input decimal must be an integer >= 0.
- Minimum base is 2.
- You will want to be careful with large integers.