You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于XQuery实现十六进制字符串转ASCII的技术求助

Got it! Converting a hex string to ASCII in XQuery is totally doable—here’s a solid implementation with explanations to help you out:

Hex to ASCII Conversion in XQuery

Core Implementation (XQuery 3.0+)

Here's a concise, readable function using arrow expressions:

declare function local:hex-to-ascii($hex as xs:string) as xs:string {
  // Validate input has even length (each ASCII char needs 2 hex digits)
  if (string-length($hex) mod 2 != 0) then
    error(xs:QName('invalid-hex'), "Hex string must have an even number of characters")
  else
    string-to-codepoints($hex)
      => every-n(2)  // Split input into 2-character hex pairs
      => map(xs:integer(concat('0x', .)))  // Convert each pair to decimal ASCII code point
      => map(xs:char(.))  // Turn decimal code into actual ASCII character
      => string-join('')  // Combine characters into a single string
};

Step-by-Step Breakdown

  • Input Check: We first make sure the hex string length is even—since every ASCII character maps to exactly two hex digits. If not, we throw a clear error to avoid broken conversions.
  • Split into Pairs: string-to-codepoints breaks the input into individual character code points, then every-n(2) groups them into the 2-digit hex pairs we need.
  • Hex to Decimal: Adding the 0x prefix tells xs:integer to treat the pair as a hexadecimal value, converting it to the decimal code point for the corresponding ASCII character.
  • Decimal to Character: xs:char takes the decimal code and returns the actual ASCII character.
  • Combine Results: Finally, we stitch all the characters together into a single readable string.

Example Usage

Test the function with a sample hex string:

let $sample-hex := "48656C6C6F20576F726C64"  // Hex equivalent of "Hello World"
return local:hex-to-ascii($sample-hex)

This will output:

Hello World

Compatibility for XQuery 1.0

If you’re working with an older XQuery version that doesn’t support arrow functions, use this FLWOR-based implementation instead:

declare function local:hex-to-ascii($hex as xs:string) as xs:string {
  if (string-length($hex) mod 2 != 0) then
    error(xs:QName('invalid-hex'), "Hex string must have an even number of characters")
  else
    string-join(
      for $char in string-to-codepoints($hex)
      group by $group-id = (position() - 1) idiv 2
      let $hex-pair := string-join($char, '')
      let $code-point := xs:integer(concat('0x', $hex-pair))
      return xs:char($code-point),
      ''
    )
};

This uses grouping to create hex pairs, achieving the same result without arrow syntax.

内容的提问来源于stack exchange,提问作者Raghu Dacha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:02:46