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.
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.
Enter a bitmask Decimal Hexadecimal
This decomposes to: 0
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>
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