Skip to content

decimal to hex

Phil Shafer edited this page Sep 10, 2013 · 2 revisions

Example: Convert decimal to hex

This example turn decimal number into hex strings.

version 1.1;

match / {
    <top> {
        <a0> { call decimal-to-hex($input = 0); }
        <a10> { call decimal-to-hex($input = 10); }
        <a100> { call decimal-to-hex($input = 100); }
        <a200> { call decimal-to-hex($input = 200); }
        <a2000> { call decimal-to-hex($input = 2000); }
        <a20000> { call decimal-to-hex($input = 20000); }
    }
}

template decimal-to-hex ($input = 0, $prefix = "0x") {
    if ($input > 0) {
        expr $prefix;
        call decimal-to-hex($input = floor($input div 16), $prefix = "");

        var $mod = $input mod 16;
        if ($mod < 10) {
            expr $mod;
        } else {
            var $hex = "abcdef";
            expr substring($hex, $mod - 9, 1);
        }
    } else if ($prefix) {
        expr $prefix _ "0";
    }
}
% slaxproc -g -E /tmp/hoo.slax
<?xml version="1.0"?>
<top>
  <a0>0x0</a0>
  <a10>0xa</a10>
  <a100>0x64</a100>
  <a200>0xc8</a200>
  <a2000>0x7d0</a2000>
  <a20000>0x4e20</a20000>
</top>
Clone this wiki locally