Search code examples
javascriptbytenibble

Best way to get two nibbles out of a byte in javascript?


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 of the file format, each byte represents one piece of information, so I have been using the following to successfully get the number values I need:

var num = str.charCodeAt(0) & 0xFF;

But I'm stuck at trying to figure out how to get the 0-16 value of the first nibble, and the same for the 2nd nibble from my single byte character "str".

Appreciate any help on this.


Solution

  • var num = str.charCodeAt(0) & 0xFF;
    var nibble1 = num & 0xF;
    var nibble2 = num >> 4;