相关疑难解决方法(0)

在c ++中将struct转换为int

我有一个结构来表示具有位字段的29位CAN标识符如下.

struct canId
{
    u8 priority         :3; 
    u8 reserved         :1; 
    u8 dataPage         :1;     
    u8 pduFormat        :8;     
    u8 pduSpecific      :8;     
    u8 sourceAddress    :8;     
} iD;
Run Code Online (Sandbox Code Playgroud)

在我的代码中,我想将此结构复制到整数变量.就像是:

int newId = iD; 
Run Code Online (Sandbox Code Playgroud)

但是我不确定这是否正确.有人可以对此发表评论吗?

编辑:我可以在每个字段上使用shift运算符,然后使用按位OR将它们放在正确的位置.但这首先使得位域结构的使用毫无用处.

c++ can-bus

6
推荐指数
1
解决办法
1504
查看次数

为什么这个联合的大小是2的位域?

我在Windows上的turbo C上工作,其中char占用一个字节.现在我的问题在于下面的联合.

union a
{
 unsigned char c:2;
}b;
void main()
{
printf("%d",sizeof(b));  \\or even sizeof(union a)
}
Run Code Online (Sandbox Code Playgroud)

该程序打印输出为2,其中union应该只占用1个字节.为什么会这样?

对于struct,它可以很好地给出1个字节但这个联合工作不正常.

还有一件事如何访问这些位字段.

scanf("%d",&b.c);  //even scanf("%x",b.c);
Run Code Online (Sandbox Code Playgroud)

没有用,因为我们不能有位的地址.所以我们必须使用下面的另一个变量

int x;
scanf("%d",&x);
b.c=x;
Run Code Online (Sandbox Code Playgroud)

我们不能避免吗?有没有其他方法???

c bit-manipulation structure unions

3
推荐指数
1
解决办法
3147
查看次数

如何评估预处理器宏中的参数以传递给sizeof?

我想有一个函数打印出有关结构的成员变量的信息.为了使函数尽可能简单(并且没有错误),我也不想手动传入类型.这使我需要能够评估传递给我的宏的参数:

#ifndef preprocessor_stringify
#define preprocessor_stringify(s) #s
#endif

typedef struct test_s {
    void (*ptr)(void*);
} test;

void doSomething_(char *name, int offset, int size){
    printf("%s %d %d\n", name, offset, size);
}

#define doSomething(name, container) (\
    doSomething_(\
        preprocessor_stringify(name),\
        offsetof(container, name),\
        sizeof(container->name))\
    );

int main(){
    doSomething(ptr, test);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这会产生编译错误 test.cpp:21:19: error: expected primary-expression before ‘->’ token sizeof(container->name))\

有想法该怎么解决这个吗?我希望解决方案兼容c和c ++,理想情况下.

c c++ c-preprocessor

3
推荐指数
1
解决办法
172
查看次数

标签 统计

c ×2

c++ ×2

bit-manipulation ×1

c-preprocessor ×1

can-bus ×1

structure ×1

unions ×1