[Solved] Defining new data types in C [closed]


What you’re looking for is bitfields, but you’ve unnecessarily mixed those with union. Remember in a union only one member exists at any time.

Also, there is not standard C type, which imho, takes 24bits or 3 bytes. So you may choose unsigned int which usually is 32 bits in size as I’ve done in this example

#include<stdio.h>

typedef struct dUnit{
  unsigned int bType : 4; // literally this could store from 0 to 15
  unsigned int bAmount : 20 ; // we've 1 byte left at this point.
  unsigned int bPaddding : 8 ;// Waste the remaining 1 byte.
}dUnit;

int main()
{
  dUnit obj;
  unsigned int x;
  printf("Enter the bType :");
  scanf("%d",&x); // You can't do &obj.bType as bType is a bit field
  obj.bType=x%15; // Not trusting the user input make sure it stays within range
  printf("Enter the bAmount :");
  scanf("%d",&x); //x is just a place holder
  obj.bAmount=x; // Again you need to filter the input which I haven't done here

  printf("Entered bType : %d\n",obj.bType);
  printf("Entered bType : %d\n",obj.bAmount);

  return 0;
}

Note : You can’t use address of operator(&) with bit-fields.

5

solved Defining new data types in C [closed]