在javascript中从一个字节中获取两个半字节的最佳方法?
我正在用 javascript 解析一个二进制文件,该文件每个字节存储两条信息,每个半字节一条信息。当然,这些值是 0-16 和 0-16。
在文件格式的所有其他部分中,每个字节代表一条信息,因此我一直在使用以下内容来成功获取我需要的数值:
var num = str.charCodeAt(0) & 0xFF;
但我一直在尝试弄清楚如何获取 0-16第一个半字节的值,以及我的单字节字符“str”中的第二个半字节的值。
感谢对此的任何帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你可以这样做:
它是如何工作的?
假设
num
的位表示为abcdwxyz
,我们希望提取abcd
作为高半字节,将wxyz
提取为低半字节蚕食。要提取低半字节,我们只需通过使用
0x0F
按位与数字来屏蔽高半字节:要提取高半字节,我们首先通过与
0xF0
按位与来屏蔽低半字节: :然后我们将结果按位右移 4 次以去掉尾随零。
按位右移变量 1 次将使其失去最右边的位并使最左边的位为零:
类似地按位右移
2
次将引入结果:和按位右移
4 次给出:
清楚地看到结果是字节的高半字节 (
abcd
)。You can do:
How does it work?
Lets suppose the bit representation of
num
isabcdwxyz
and we want to extractabcd
as higher nibble andwxyz
as lower nibble.To extract the lower nibble we just mask the higher nibble by bitwise anding the number with
0x0F
:To extract the higher nibble we first mask the lower nibble by bitwise anding with
0xF0
as: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:
Similarly bitwise right shifting
2
times will introduce result in :and bitwise right shift
4
times gives:as clearly seen the result is the higher nibble of the byte (
abcd
).因为我喜欢这个,所以我想添加一些我刚刚写的可能有用的东西。也许其他人也会发现它很有用。
下面的 jsFiddle
原型:
调用示例:
刚刚添加以获得可能的帮助,但在上面没有使用:
Since I'm favoriting this, I wanted to add some things I just wrote that might be useful. Perhaps others will find it useful as well.
Below's jsFiddle
Prototypes:
Example Calls:
Just added for possible help, but is not used in the above:
将字符串转换为缓冲区,然后转换为乳头:
Convert the string to buffer and then nipples: