简体   繁体   English

类型转换到位字段

[英]Typecasting to a bit-field

I am trying to assign a value to a bit field in a struct. 我试图将一个值分配给结构中的位字段。 It is a demotion since the assigned variable is of a smaller size than the type used on the right hand side. 这是降级的,因为所分配的变量的大小小于右侧使用的类型。 Is there a way to force typecast it, understanding that there is some risk in demotion. 有一种方法可以强制改型,但要了解降级存在一定风险。 This is test code, and I do not expect the right hand value to ever be greater than what my bit field can take. 这是测试代码,我不希望右手值大于我的位字段可以接受的值。

Compiling using: 编译使用:

    gcc -Wconversion compileError.c

Code: 码:

#include "stdio.h"

typedef unsigned long  int uint64_t;
typedef unsigned short int uint16_t;

typedef struct
{
    uint64_t  val:48;
    uint16_t  length;
}data_t;

static data_t testData[10] = {};

int main()
{
    data_t*   pData = (data_t*)&testData;
    uint64_t  var   = 0;

    pData->val = var + 1;

    printf("Just trying to compile this program\n");
    return 0;
}

Compiler Output: 编译器输出:

compileError.c: In function main:
compileError.c:19:22: warning: conversion to long unsigned   
int:48 from uint64_t may alter its value [-Wconversion]
 pData->val = var + 1;

This blog shows how you can temporarily silence that warning. 博客显示了如何暂时使该警告静音。

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wconversion"
    pData->val = var + 1;
#pragma GCC diagnostic pop

There's an open GCC Enhancement Request to address this, and there's a comment showing a workaround using masking. 有一个开放的GCC增强请求可以解决此问题,并且有一条注释显示了使用掩膜的解决方法。

pData-> val = (var + 1) & 0xffffffffffffLU

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM