Okay, so you know how strings are made up of characters, and all those characters are made up of a single byte each. Assuming I'm using a string to represent a ton of bits, how can I get the values for a range of the bits? So say, I wanted the bits from 2 to 13 for some obscure reason, how can I take my string and extract all of the bits in that range?
As an example, "FF"
is 0000111100001111
in binary. If I wanted to select bits 2 -> 13 in that, I'd get 000111100001
. And then somewhere along the line somebody decides whether to pad the 0s to the left or to the right when converting it back to the string but that's not a problem.
Extra useful if an explanation includes how to turn the range into a boolean array (I have a solution for this bit but it's not particularly efficient).
If you're needing a use case, I'm planning on creating my own replication because Roblox networking sucks.
Right, seems like I have came up with some seemingly efficient solution which returns the bits as table of booleans.
First thing you should do, is find the bytes that fall within the begin and end bit range, so no processing power is wasted converting unnecessary bytes to bits. After that is done, you can start converting the bytes into bits.
01 | function getBits( str, beginBit, endBit ) |
02 | -- A reference table for bit values(reading from table is significantly faster than using power operator) |
03 | local byte_t = { 1 , 2 , 4 , 8 , 16 , 32 , 64 , 128 } |
04 |
05 | -- Finding out actual bytes that we are interested in |
06 | local beginChar = math.ceil( beginBit/ 8 ) |
07 | local endChar = math.ceil( endBit/ 8 ) |
08 | local range = str:sub( beginChar, endChar ) |
09 |
10 | -- I will convert and directly set the captured bits, so there is no reason to loop several times and what not |
11 | local bits = { } |
12 | -- Since I will directly store the result, I need to know from which bit should I start storing |
13 | local beginOffset = beginBit% 8 - 1 |
14 | -- Same applies to the end |
15 | local endOffset = endBit - beginOffset + 1 |
Tried my best to comment it, but I don't have much experience with these sort of manipulations and I'm too sleepy right now.