如何有效地读出位字节? [英] How to efficiently read bits out of bytes?

查看:143
本文介绍了如何有效地读出位字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在包含的WebSockets和服务器(Node.js的)和客户端(浏览器)之间的数据一个项目使用自定义的(很简单)格式进行数据交换我设置了发送。

I'm working on a project that includes WebSockets, and data between the server (Node.js) and the client (Chrome) is sent using a custom (very simple) format for data exchange I set up.

我在3位因为我送这都有可能8件物品发送数据。数据格式如下:

I'm sending data in pieces of 3 bits because I'm sending items which all have 8 possibilities. The data format looks like this:

            0          1
bit index   01234567 8901...
item        aaabbbcc cddd...

目前,我解析的项目出来的字节是这样的:

Currently, I'm parsing the items out of the bytes like this:

var itemA = bytes[0] >> 5;
var itemB = (bytes[0] >> 2) & 7;
var itemC = (bytes[0] & 3) << 1 | bytes[1] >> 7;
var itemD = (bytes[1] >> 4) & 7;

就个人而言,这种感觉是过于复杂。问题是,这只是复杂的,因为我得到以字节为单位,这是8的倍数解析出3位的项目的数据我有位移,做的和操作,因为8是不是被3整除我有时甚至要像两个字节的部分结合起来, itemC

这将是更有效的以读取该数据作为3比特代替8位组的组

It would be much more effective to read this data as groups of 3 bits instead of groups of 8 bits.

我想出用的ToString(2),然后用 .substring <被全部转换成字节位串/ code>来获取长度3,和转换回数字与 parseInt函数(比特串,2)一子,但我想这是不是做的方式它,因为字符串操作是缓慢的,我其实没有做任何字符串相关的。

What I've come up with is converting all bytes into bits to a string using .toString(2), then using .substring to get a substring with length 3, and converting back to a number with parseInt(bitString, 2), but I guess that's not the way to do it, since string manipulation is slow and I'm actually not doing anything string-related.

是否有可能读取的例如组位3,而不是从字节解析呢?或者是有读出位字节更有效的方法?

Is it possible to read bits in groups of e.g. 3 instead of parsing them from bytes? Or is there a more efficient way to read bits out of bytes?

推荐答案

二进制AND和位移位操作是这样做的最快方法。他们很好地翻译成机器code指令。进一步加快这的唯一方法是通过例如牺牲速度的带宽根本无法使用每字节超过3位,但是从你的问题来看你可能已经考虑,并拒绝了权衡。

The binary AND and bit shifting operations are the fastest way of doing this. They translate well into machine code instructions. The only way to further speed this up is by sacrificing bandwidth for speed by for example simply not using more than 3 bits per byte, but judging from your question you've probably already considered and rejected that tradeoff.

这篇关于如何有效地读出位字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆