-1

I'm assured that I get numbers from 0-7, and I'm interested to make the code as efficient as possible. I want to input only the three most least significant bits into the binary file, and not the whole byte. Is there anyway I can write only 3 bits? I get a huge number of numbers... The other way I found is to try to mash up the numbers (00000001 shl 3 & next number) Though there's always a odd one out.

1 Answer 1

3

Files work at a byte level, there's no way to output single bits1. You have to read the original bytes containing the bits of your interest, fix them with the bits you have to modify (using bitwise operations) and write them back where they were.


1. And it would not be efficient to do so anyway. Hard disks work best with large chunks to write; flash disks actually require to work with large blocks (=> a single bit change requires a full block erase and rewrite); they are some reasons why operating systems and disk controllers do a lot of write caching.

2
  • I'm not trying to be accurate on the 3rd bit, but for example an array of 3 ints that total to 24 bits may be written to only 16 bits (3x3 + padding) the idea is to save memory May 17, 2016 at 6:51
  • 2
    @Dreggman45: you can stuff 10 3bit groups in a single 32bit int - saves space, but all accesses (read & write) to the data now require shifts and masks. Make sure you actually need that amount of space savings and that the costs associated are ok. (Also using 4bit groups would make your code quite a bit simpler.)
    – Mat
    May 17, 2016 at 6:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.