Thread: typedef struct problem

  1. #1
    Registered User
    Join Date
    Jan 2011
    Posts
    2

    Unhappy typedef struct problem

    Code:
    typedef struct 
    {
    unsigned char
    b0:1,b1:1,b2:1,b3:1,b4:1,b5:1,b6:1,b7:1;
    }
    bitset;
    So I got a struct consisting of a char with 8x1bit identifiers.

    For example I'll make 50 of them.
    Code:
    bitset* collection = calloc(50, 1);
    Now giving each char binary data.
    Code:
    for (i = 0; i < 50; i++)
    {
        collection[i].b0 = 1;    collection[i].b1 = 0;
        collection[i].b2 = 0;    collection[i].b3 = 1;
        collection[i].b4 = 1;    collection[i].b5 = 0;
        collection[i].b6 = 1;    collection[i].b7 = 1;
    }
    The values aren't irrelevant, I just want to know if there's a way of looping through the bits to manipulate them. Here's a concept snippet:
    Code:
    for (i = 0; i < 50; i++)
    {
        for (j = 0; j < 8; j++)
        {
            collection[i].j = 1;
        }
    }
    That's obviously not the way to go but do you think it involves naming the identifiers something else?
    Please enlighten me fellow programmers

  2. #2
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    Is there a need to be one?
    If you want some additional feature: built a function yourself.

    Code:
    SetBitset(bitset* b, int b0, int b1, int b2, ...)
    {
        int i;
        for (i = 0; i < 8; ++i)
        {
           b.b0 = b0;
           ...
         }
    }
    If you want to make a function that sets everything to something you can do so as well.

    You could try this:
    Code:
    struct bitset
    {
      ....
    }
    typedef union
    {
         struct bitset bits;
         unsigned char value;
    } Bitset;
    
    ...
    Bitset a;
    a.value = 0xFF; //all bits to 1
    a.bits.b0 = 0; //bit 0 to 0
    Not sure if you can use a struct inside a union. If you can then in this way you can manipulate the bits of a byte more easily which is probably what you want.

  3. #3
    Registered User
    Join Date
    Jan 2011
    Posts
    2

    Lightbulb cheers

    thanks very much it's just what I needed

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling C in Visual Studio 2005
    By emanresu in forum C Programming
    Replies: 3
    Last Post: 11-16-2009, 04:25 AM
  2. Replies: 8
    Last Post: 06-04-2009, 02:03 PM
  3. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 08:18 PM
  4. pointer problem or so...
    By TL62 in forum C Programming
    Replies: 19
    Last Post: 01-12-2008, 11:45 PM
  5. Problem with typedef struct
    By cprogrammer_18 in forum C Programming
    Replies: 2
    Last Post: 02-03-2006, 06:01 AM

Tags for this Thread