Ranjith Reddy
Ranjith Reddy

Reputation: 129

String join using xquery

We have a requirement to convert hexadecimal to binary. After good research we are able to achieve it, but the problem is the output has spaces between each set of binary elements.

How to remove these spaces?

Below code gives output as: 0111 0110 0010 0100

Required: 0111011000100100


xquery version "1.0" encoding "utf-8"
(:: OracleAnnotationVersion "1.0" ::)
declare namespace ns1="http://www.s2mpos.com/v1";
(:: import schema at "s2miso8583.xsd" ::)
declare namespace bin="http://expath.org/spec/binary";
declare variable $ReadLine as xs:string external;
declare function local:charsReturn($arg as xs:string) as xs:string*
{
  for $ch in string-to-codepoints($arg)
  return codepoints-to-string($ch)
};

declare function local:convertString($argx as xs:string) as xs:string*
{ 
  let $x := local:charsReturn($ReadLine)
       for $a in $x
       return
         string-join(
          for $b in (8,4,2,1)
          let $cv := xs:integer($a)
          let $xm := $cv mod ($b*2)
          return
            if ( $xm >= $b ) then "1" else "0"
        ,"")
};

declare function local:func($ReadLine as xs:string) as element() (:: schema-element(ns1:s2mMessages) ::) {
  <ns1:s2mMessages>
    {
      let $abc := local:convertString($ReadLine)
    } 
  </ns1:s2mMessages>
};

local:func($ReadLine)

Upvotes: 0

Views: 548

Answers (1)

Michael Kay
Michael Kay

Reputation: 163322

I don't see how your code can work. If $Readline contains hex digits then $a can be any hex digit, for example "C", and if $a is "C" then xs:integer($a) will fail with FORG0001.

I would do:

string-join(
  let $hex := ('0', '1', '2', '3', ... 'E', 'F')
  let $bin := ('0001', '0010', '0011', '0100', ...., '1110', '1111')
  for $a in local:charsReturn($ReadLine)
  return $bin[index-of($hex, $a)], "")

Upvotes: 1

Related Questions