I am working on a project that includes WebSockets, and the data between the server (Node.js) and the client (Chrome) is sent using a custom (very simple) data exchange format that I configured.
I send data in pieces of 3 bits, because I send elements that have 8 possibilities. The data format is as follows:
0 1 bit index 01234567 8901... item aaabbbcc cddd...
I am currently parsing elements from bytes as follows:
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;
Personally, this seems too complicated. The problem is that it is complex, because I get data in bytes that are multiples of 8. To parse elements from 3 bits, I need to perform a bit shift by performing AND operations and because 8 is not divisible by 3 I sometimes you even have to combine parts of two bytes, for example, for itemC .
It would be much more efficient to read this data as groups of 3 bits instead of groups of 8 bits.
What I came up with is converting all bytes to bits into a string using .toString(2) and then using .substring to get a substring of length 3 and converting back to a number using parseInt(bitString, 2) , but I suppose this is not a way to do this, as string manipulation is slow, and I am not actually doing anything related to the string.
Is it possible to read bits in groups, for example. 3 instead of parsing them from bytes? Or is there a more efficient way to read bits from bytes?
pimvdb
source share