portable bitfields

This is a discussion on portable bitfields within the C++ Programming forums, part of the General Programming Boards category; I want to make some portable bitfield for writing to a file, however from what I've read they are very ...

  1. #1
    Unregistered User Yarin's Avatar
    Join Date
    Jul 2007

    portable bitfields

    I want to make some portable bitfield for writing to a file, however from what I've read they are very unprotable and have no address. So I was thinking that maybe seperate structers for each bitfield type would fix that problem.
    struct sMyVar {
       unsigned field :4;
    sMyVar myVar;
    So would a pointer to myVar unltimitaly point to my half byte? Also, would writting 2 of them to a file end of being a complete byte, or a two bytes, half of each of which are blank?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    The problem is, if you try to write myVar to a file, you're going to get all the invisible padding bits as well. Any operation you try on the whole structure will always get all the padding as well.

    Also, there isn't a sure way of knowing what underlying data type the compiler chooses to store bit-fields in. So sizeof(myVar) might be sizeof(char) or sizeof(long).

    Also, there is no way to know (or control) how the bit-fields are arranged. For example, your :4 field might be stored in an unsigned long with a mask of 0xF0000000 or a mask of 0x0000000F.

  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Farncombe, Surrey, England
    Most compilers will make a 4-bit field take up one byte, where four bits are undefined (not necessarily zero). A second 4-bit field next to it will take up another byte with four unused bits.

    If you want to store 4-bit fields in a file, then you're best of making multiple 4-bit fields into a single structure (2, 4 or 8 for example). I don't think you can make arrays of bitfields - maybe you can - it would certainly make it easier.

    Alternatively, just pack by hand into a 8, 16 or 32-bit integer using shifts - that will have the benefit of being more likely to be portable too - particularly if you expect this code to work on both little-endian and big-endian machines.


Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 05-14-2009, 03:48 PM
  2. making it portable.....?
    By ShadeS_07 in forum C Programming
    Replies: 11
  3. C - Portable?
    By vb.bajpai in forum C Programming
    Replies: 2
    Last Post: 07-15-2007, 10:09 AM
  4. which Portable mp3 player?
    By Raihana in forum A Brief History of Cprogramming.com
    Replies: 27
  5. Portable nonbusy hold?
    By Imperito in forum C Programming
    Replies: 2
    Last Post: 09-06-2002, 12:48 PM
