Xquery 中的 Ascii 到十六进制转换

Ascii to Hex conversion in Xquery

我需要使用 XQuery 将 ASCII 转换为十六进制字符串,请帮助提供任何相应的参考或代码片段以实现此功能,例如我有字符串:1239565447854,我需要转换十六进制:31323339353635343437383534

您可以使用 string-to-codepoints() to get the numeric codepoint for each character. For each codepoint, determine how many times it is divisible by 16 using idiv, and the remainder using the mod 运算符。对于这两个数字,通过在 16 个字符的序列中按位置查找来获取它们的十六进制值,然后加入结果:

declare function local:codepoint-to-hex($codepoint as xs:integer) as xs:string {
  let $hex-index := ("0123456789ABCDEF" => string-to-codepoints()) ! codepoints-to-string(.)
  let $base16 := $codepoint idiv 16
  let $remainder := $codepoint mod 16
  return 
    string-join((
      $hex-index[$base16 + 1],
      if ($remainder = 0) 
      then ()
      else $hex-index[$remainder + 1]
      ), "")
};

declare function local:string-to-hex($str as xs:string) as xs:string {
  string-join( string-to-codepoints($str) ! local:codepoint-to-hex(.), "")
};

local:string-to-hex('1239565447854')