将char转换为4位的位字段项 [英] Cast char to a bit field entry of 4 bits

查看:41
本文介绍了将char转换为4位的位字段项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我遇到了另一个问题,我正在研究单个位并从ascii文本中提取数据。问题是编译器给我一个错误,那就是将char(8位)强制转换为4位内存字段可能会更改其值。

Hello guys I'm facing another problem, I'm working on single bits and extract data from ascii text. The problem is that the compiler gives me an error about the fact that casting a char (8 bits) to a 4 bit memory field may alter its value.

显然,这是真的但是我该如何克服这个错误?

Obviously that's true but how could I overcome that error?

typedef struct {
struct {
    unsigned int type:        4;
    unsigned int uid:         8;
    unsigned int operation:   4; 
    unsigned int reg:         16;
}header;
char *arg_nm;
} OWL_request;

完整错误:

 error: conversion to 'unsigned char:4' from 'char' may alter its value [-Werror=conversion]

这是赋值

request.header.type = (char)(j[0]-65);

j * char

我要做的是摆脱错误而不更改编译器标志

What I have to do is to get rid of the error without altering compiler flags

推荐答案

使用gcc,您可以通过将值屏蔽为您分配给的位域中的位数来摆脱警告,因为 type 是4位,您可以这样做:

With gcc, you can get rid of the warning by masking the value to the number of bits in the bitfield you assign to, since type is 4 bits, you can do:

request.header.type = (unsigned)(j[0]-65) & 0xf;

(请注意,关于为什么不应该使用位域,您可以找到一些很好的论据,例如< a href = https://stackoverflow.com/questions/6043483/why-bit-endianness-is-an-issue-in-bit-fields>此处,而应使用纯整数和比特稀疏的建议@LPs)

(Note that you can find several good arguments as to why you should not use bitfields , see e.g. here , and instead use plain integers and bit twiddling as suggested by @LPs)

这篇关于将char转换为4位的位字段项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆