Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Decompose a bitmask into bits

0.00/5 (No votes)
4 Aug 2015 1  
A simple tool to allow you to decompose bitmask values into its bits.

This article may contain live JavaScript that has been reviewed and tested for security. If you wish to submit articles containing JavaScript please email your submissions to submit@codeproject.com.

Introduction

I use bitmasks far less than I used to, but when I do use them I often have the need to decompose a value into its parts.

The BitDemaskerer

Enter a bitmask  

This decomposes to: 0

The Code

Super simple:

<p>Enter a bitmask <input id="bitmask" onkeyup="GetBits()" style="width:100px;font-size:20px" type="text" />  
<input type="radio" id="Dec" name="outputFormat" value="dec" checked="true" onchange="GetBits()" /><label for="Dec">Decimal</label>
<input type="radio" id="Hex" name="outputFormat" value="hex" onchange="GetBits()" /><label for="Hex">Hexadecimal</label>
</p>

<p>This decomposes to: <span id="result">0</span></p>

<script type="text/javascript">
    function GetBits() {
		var hex = document.getElementById("Hex").checked;
        var elm = document.getElementById("bitmask");
        var value = parseInt(elm.value);
        if (isNaN(value))
            result.innerHTML = "Not a number";
        else {
            result.innerHTML = "";
            for (var i = 1; i <= value; i = i * 2)
                if ((value & i) > 0)
				{
					var bitRepresentation = hex? "0x" + i.toString(16) : i.toString();
                    result.innerHTML += (result.innerHTML == "" ? "" : ", ") + bitRepresentation;
				}
        }
    }
</script>

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here