在C中定义新数据类型

时间:2016-12-13 17:20:11

标签: c

我需要在项目中定义一些新的数据类型,以便清除和快捷我的代码,因为我需要经常使用这些类型。

我知道我必须使用typedefunion,但我不会记得很清楚。

一个例子:

variable name: dUnit,
length: 3 bytes,
Subdivided into... 
bType->4 MSB,
bAmount->20 LSB

就像是......

typedef struct dUnit
{
  int bType: 4;
  int bAmount: 20;
}dUnit;

另一个例子:

Variable name: dAddressType,
length: 3 bytes,
Not subdivided.

typedef unsigned char dAddressType[3];

我还没有使用过一段时间的C,现在我正在努力实现非常简单的任务。

什么是正确的语法?

1 个答案:

答案 0 :(得分:1)

您正在寻找的是位域,但是您与union进行了不必要的混合。请记住,在union中,任何时候都只有一名成员存在。

此外,没有标准的C类型,即imho,需要24位或3个字节。因此,您可以选择通常为32位的unsigned int,就像我在此示例中所做的那样

#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;
}

注意:您不能将运算符地址(&)与位字段一起使用。

相关问题