I\'m parsing a binary file in javascript that is storing two pieces of information per byte, one per nibble. The values are, of course, 0-16 and 0-16.
In all other parts
You can do:
var num = str.charCodeAt(0);
var lower_nibble = (num & 0xF0) >> 4;
var higher_nibble = num & 0x0F;
How does it work?
Lets suppose the bit representation of num
is abcdwxyz
and we want to extract abcd
as higher nibble and wxyz
as lower nibble.
To extract the lower nibble we just mask the higher nibble by bitwise anding the number with 0x0F
:
a b c d w x y z
&
0 0 0 0 1 1 1 1
---------------
0 0 0 0 w x y z = lower nibble.
To extract the higher nibble we first mask the lower nibble by bitwise anding with 0xF0
as:
a b c d w x y z
&
1 1 1 1 0 0 0 0
---------------
a b c d 0 0 0 0
and then we bitwise right- shift the result right 4 times to get rid of the trailing zeros.
Bitwise right shifting a variable 1 time will make it loose the rightmost bit and makes the left most bit zero:
a b c d w x y z
>> 1
----------------
0 a b c d w x y
Similarly bitwise right shifting 2
times will introduce result in :
a b c d w x y z
>> 2
----------------
0 0 a b c d w x
and bitwise right shift 4
times gives:
a b c d w x y z
>> 4
----------------
0 0 0 0 a b c d
as clearly seen the result is the higher nibble of the byte (abcd
).