Reputation: 1748
I am trying to decode a series of hex strings and check some of their nibbles.
In the example below, I am checking string (hexString
) and checking it if the last 5 bits are set to true (0x1f). However, it is returning false
. How can I check a hex string's bits?
const hexString = 'f0'
const areFiveLowestBitsSet = (hexString && 0x1f) === 0x1f
console.log(areFiveLowestBitsSet) // prints true
Upvotes: 1
Views: 2219
Reputation: 1074258
There are two problems:
You're not parsing the string to get a number
You're using &&
, which is a logical operator, not the bitwise operator &
Parse the number as hex (parseInt(hexString, 16)
) and use the bitwise operator:
let hexString = 'f0'
let areFiveLowestBitsSet = (parseInt(hexString, 16) & 0x1f) === 0x1f;
// −−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^^−^
console.log(areFiveLowestBitsSet); // false
hexString = '3f';
areFiveLowestBitsSet = (parseInt(hexString, 16) & 0x1f) === 0x1f;
// −−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^^−^
console.log(areFiveLowestBitsSet); // true
Upvotes: 1