I want to compress data and I have a lot of bytes that are either ones or zeros. I have never had to convert data into bits, but I was wondering if this method would work below:
incoming.data[] is an array of the bytes that are either 0 or 1. and incoming.length is how many items there are. I initialized them to 255, to make sure they are all 1s when I "&" them.
napkinsterror:
I was wondering if this method would work below:
Seems like it would take much less time to test it yourself than it would take to make a forum post, have someone else test it, and report back whether it works or not.
Rather than writing the results to separate byte variables, you could define a byte array that was one eighth the length of the source array (rounded up) and then use input / 8 to get the index into the output byte array and input % 8 to get the bit number within that byte. Then you can use a single assignment in the for loop to handle all bits of all bytes.
PeterH:
Rather than writing the results to separate byte variables, you could define a byte array that was one eighth the length of the source array (rounded up) and then use input / 8 to get the index into the output byte array and input % 8 to get the bit number within that byte. Then you can use a single assignment in the for loop to handle all bits of all bytes.
If you are worried about low level optimization, the compiler will generate better code for input / 8 and input % 8 if input is an unsigned type (the first is done as a shift right by 3 and the second is done via an AND instruction). If it is signed, it has to generate extra code to deal with the sign.