Testing Bits

Problem

You want to treat numbers as bit masks even though XSLT does not have integers or associated bitwise operators.

Warning

When working with XML, don’t go out of your way to encode information in bits. Use this solution only when you have no control over the encoding of the data.

Solution

The following solution works on 16-bit numbers, but can easily be extended up to 32:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" id="bittesting"> <!--powers of two--> <xsl:variable name="bit15" select="32768"/> <xsl:variable name="bit14" select="16384"/> <xsl:variable name="bit13" select="8192"/> <xsl:variable name="bit12" select="4096"/> <xsl:variable name="bit11" select="2048"/> <xsl:variable name="bit10" select="1024"/> <xsl:variable name="bit9" select="512"/> <xsl:variable name="bit8" select="256"/> <xsl:variable name="bit7" select="128"/> <xsl:variable name="bit6" select="64"/> <xsl:variable name="bit5" select="32"/> <xsl:variable name="bit4" select="16"/> <xsl:variable name="bit3" select="8"/> <xsl:variable name="bit2" select="4"/> <xsl:variable name="bit1" select="2"/> <xsl:variable name="bit0" select="1"/> <xsl:template name="bitTest"> <xsl:param name="num"/> <xsl:param name="bit" select="$bit0"/> <xsl:choose> <xsl:when test="( $num mod ( $bit * 2 ) ) - ( $num mod ( $bit ) )">1</xsl:when> <xsl:otherwise>0</xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template name="bitAnd"> <xsl:param name="num1"/> <xsl:param name="num2"/> <xsl:param ...

Get XSLT Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.