Thread: Writing binary data to a file (bits).

  1. #1
    Welcome to the real world
    Join Date
    Feb 2004
    Posts
    50

    Writing binary data to a file (bits).

    I'm under the assumption that the smallest amount of data you can write to a file is a byte - 4 bits. I have a problem, working with a compressed file, that I need to solve.

    I have the algorithm and everything, but I'm stuck on two parts, which I could not find supporting information for. I need to be able to read 3 bits from a file and then from that number, determine how many bits to write out - from 1-6.

    How can I possibly write out a variable amount of bits? I figure that if I need to read 3 bits from a file, I can just read in a char (4 bits), take those 4 bits, and do bit operations on them to single what it would be if it were just a 3 bit object.

    Does anybody have any ideas/suggestions? Thanks.

    p.s. I'm not writing any code at the moment, I'm just trying to get the design details down.

  2. #2
    C > C++ duders ggs's Avatar
    Join Date
    Aug 2001
    Posts
    435
    you use bitwise operators, like &, |, <<, >> and the like.

    you'll still have to deal with your file access operations in bytes, but you can pack these bytes with variable-sized bitfields.

    it's barrels of fun!
    .sect signature

  3. #3
    Registered /usr
    Join Date
    Aug 2001
    Location
    Newport, South Wales, UK
    Posts
    1,273
    Erm, a byte is actually 8 bits, on the Intel x86 platform and many others, at least.

    It's a common problem that can be overcome by the use of bit masking and shifting. Let's suppose you wanted the first 3 bits from a char/unsigned char (8 bits):-
    Code:
    0 1 0 1 0 1 0 1
    \___/
    In order to get those bits in C, you'd read the byte in, mask it so only the top 3 bits are relevant and shift it 5 bits to the right so the bits are at the bottom and will be arithmatically correct:-
    Code:
    unsigned char byte, bits;
    
    byte = getc(fp);
    bits = (byte & 0xE0) >> 5;
    That'll give you a value of 0 to 7 for your three bits.

    You can ignore the mask and just shift if you don't need anything else from those 8 bits.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 48
    Last Post: 09-26-2008, 03:45 AM
  2. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM
  3. Binary Tree, couple questions
    By scoobasean in forum C Programming
    Replies: 3
    Last Post: 03-12-2005, 09:09 PM
  4. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  5. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM