[英]Compare hex string
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).在下面的示例中,我正在检查字符串 ( hexString
) 并检查最后 5 位是否设置为 true (0x1f)。 However, it is returning false
.但是,它返回false
。 How can I check a hex string's bits?如何检查十六进制字符串的位?
const hexString = 'f0'
const areFiveLowestBitsSet = (hexString && 0x1f) === 0x1f
console.log(areFiveLowestBitsSet) // prints true
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:将数字解析为十六进制( parseInt(hexString, 16)
)并使用按位运算符:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.