NO

Author Topic: A struct & bitprecising question  (Read 3290 times)

andre104

  • Guest
A struct & bitprecising question
« on: July 17, 2007, 12:58:32 AM »
Found this from the FreePascal board ...

Code: [Select]
#include <stdio.h>

struct bitprecising {
char ch : 8;
int n : 2;
long l : 3;
};

int main(){
struct bitprecising x;
struct bitprecising *p;

p = &x;
(*p).ch = 'a';
(*p).n = 1;
(*p).l = 2L;

printf("x.ch = %c\n",x.ch);
printf("x.n = %d\n",x.n);
printf("x.l = %ld\n",x.l);

return 0;
}

What does that struct do ? And BTW, what is this bitprecising stuff ?

Offline frankie

  • Global Moderator
  • Member
  • *****
  • Posts: 2113
Re: A struct & bitprecising question
« Reply #1 on: July 17, 2007, 01:28:23 PM »
The forum user is simply asking if it's possible to define "bit fields" in pascal structures as in C.
The code you posted is a sample for a C bit_fields structure.
The bit_field is a structure member which bit width is specified by user. In the sample above the member 'a' is of type char and its width is set to 8 bits, then you have an integer 'n' made of 2 bits and a long 'l' composed of 3 bits. In this case the compiler will pack together the bits in a DWORD multiples.
In our case the whole structure will fit in a single double word, where bit 0 to bit 7 will host the char 'a', bit 8 to bit 9 will host an integer, bit 10 to bit 12 will host a long and the remaining bits are unused.
The compiler automatically extract and reinsert correct bits when you use them in your code.

For more info google "C language bit field"
"It is better to be hated for what you are than to be loved for what you are not." - Andre Gide