gpt4 book ai didi

c - 在 C 中定义新数据类型

转载 作者:行者123 更新时间:2023-11-30 21:43:32 24 4
gpt4 key购买 nike

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

我知道我必须使用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 语言了,现在我正在努力完成非常简单的任务。

正确的语法是什么?

最佳答案

您正在寻找的是位域,但您不必要地将它们与union混合在一起。请记住,在联盟中任何时候都只存在一名成员。

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

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

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

关于c - 在 C 中定义新数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41126977/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com