Reputation: 181
I want a function that take 2 parameters,
first param is input decimal,
second param is base (16 for hex conversion, 8 for octal conversion)
The function should return the converted value
Upvotes: 3
Views: 245
Reputation: 4241
Here is how you can do it yourself using a recursive user-defined function (and a second one as a convenience wrapper):
declare function local:to-base($value as xs:integer, $base as xs:integer) as xs:string {
if($base lt 2 or $base gt 16) then error((), 'Base must be between 2 and 16, found ' || $base)
else if($value ge 0) then local:to-base($value, $base, ())
else '-' || local:to-base(-$value, $base, ())
};
declare function local:to-base($value, $base, $out) {
let $last := $value mod $base,
$rest := $value idiv $base
let $new-out := (if($last lt 10) then $last + 48 else $last + 55, $out)
return if($rest eq 0) then codepoints-to-string($new-out)
else local:to-base($rest, $base, $new-out)
};
You can invoke it just as you describe:
local:to-base(511, 16), (: yields '1FF' :)
local:to-base(-123, 3) (: yields '-11120' :)
Upvotes: 3