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

Viewed 6006

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.

4 Answers

Convert the string to buffer and then nipples:

function bufferToNibbles(key) {
  // this will convert ascii string to hex values 
  // buffer will get sequence of bytes
  const buffer = Buffer.from(key);
  const nibbles = [];
  for (let i = 0; i < buffer.length; i++) {
    let q = i * 2;
    nibbles[q] = buffer[i] >> 4;
    ++q;
    nibbles[q] = buffer[i] % 16;
  }
  return nibbles;
}
Related