Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can do:</p> <pre><code>var num = str.charCodeAt(0); var lower_nibble = (num &amp; 0xF0) &gt;&gt; 4; var higher_nibble = num &amp; 0x0F; </code></pre> <p>How does it work?</p> <p>Lets suppose the bit representation of <code>num</code> is <code>abcdwxyz</code> and we want to extract <code>abcd</code> as higher nibble and <code>wxyz</code> as lower nibble.</p> <p>To extract the lower nibble we just mask the higher nibble by bitwise anding the number with <code>0x0F</code>:</p> <pre><code>a b c d w x y z &amp; 0 0 0 0 1 1 1 1 --------------- 0 0 0 0 w x y z = lower nibble. </code></pre> <p>To extract the higher nibble we first mask the lower nibble by bitwise anding with <code>0xF0</code> as:</p> <pre><code>a b c d w x y z &amp; 1 1 1 1 0 0 0 0 --------------- a b c d 0 0 0 0 </code></pre> <p>and then we bitwise right- shift the result right 4 times to get rid of the trailing zeros. </p> <p>Bitwise right shifting a variable 1 time will make it loose the rightmost bit and makes the left most bit zero:</p> <pre><code>a b c d w x y z &gt;&gt; 1 ---------------- 0 a b c d w x y </code></pre> <p>Similarly bitwise right shifting <code>2</code> times will introduce result in :</p> <pre><code>a b c d w x y z &gt;&gt; 2 ---------------- 0 0 a b c d w x </code></pre> <p>and bitwise right shift <code>4</code> times gives:</p> <pre><code>a b c d w x y z &gt;&gt; 4 ---------------- 0 0 0 0 a b c d </code></pre> <p>as clearly seen the result is the higher nibble of the byte (<code>abcd</code>).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload