简体   繁体   English

在C中使用带有位运算符的小整数

[英]Use of small integer with bits operator in C

Related to a previous question , I can't understand some rules of MISRA C 2004. 之前的问题相关 ,我无法理解MISRA C 2004的一些规则。

In ISO C99 draft 2007 , in 6.5 section §4 : ISO C99 2007草案中 ,在6.5节§4中:

Some operators (the unary operator ~, and the binary operators <<, >>, &, ^, and |, collectively described as bitwise operators) are required to have operands that have integer type. 一些运算符(一元运算符〜,以及二元运算符<<,>>,&,^和|,统称为按位运算符)需要具有整数类型的操作数。 These operators yield values that depend on the internal representations of integers, and have implementation-defined and undefined aspects for signed types. 这些运算符产生的值取决于整数的内部表示,并且具有已签名类型的实现定义和未定义方面。

Ok, using a signed integer with bitwise operators can produce undefined behaviour (and makes no sense). 好吧,使用带位运算符的有符号整数可能会产生未定义的行为(并没有任何意义)。

A good solution is to use explicit conversion to a wider unsigned integer type in order to by-pass integral promotion, and then not use signed value with bitwise operators (see associated answers of my previous question). 一个好的解决方案是使用显式转换为更宽的无符号整数类型,以便绕过整数提升,然后不使用带符号运算符的有符号值(请参阅我之前问题的相关答案)。

But in MISRA C 2004, use of small unsigned integers with bitwise operators is possible (rule 10.5 for example). 但是在MISRA C 2004中,可以使用带位运算符的小型无符号整数(例如规则10.5)。 Why, if integral promotion leads to use signed values with bitwise operators? 为什么,如果整数提升导致使用带位运算符的带符号值? I think I don't understand some things. 我想我不明白一些事情。

The rules don't contradict each other and you don't need to widen the type. 这些规则并不相互矛盾,您不需要扩大类型。 You can immediately cast the result of small integer binary operation back to its type. 您可以立即将小整数二进制运算的结果转换回其类型。

A small integer will not be promoted to int for shifts unless the first operand is int. 除非第一个操作数为int,否则不会将小整数提升为int。

This is from their example: 这是他们的例子:

uint8_t port = 0x5aU;
uint8_t result_8;
uint16_t result_16;

result_8 = (~port) >> 4;  /* not compliant */
result_8 = ((uint8_t)(~port)) >> 4; /* compliant */
result_16 = ((uint16_t)(~(uint16_t)port)) >> 4; /* compliant */

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

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