O'Reilly logo

XSLT Cookbook by Sal Mangano

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required