c - Cast from "int" to "unsigned short" after applying bitwise operator "~" -
static analysis tool utilize raises warning code :
uint16 var1 = 1u; uint16 var2 = ~var1;
i check misra c 2004 rules , find 10.5 rule :
if bitwise operators ~ , << applied operand od underlying type unsigned char or unsigned short, result shall cast underlying type of operand.
ok, it's not problem, implicit cast applied (i think "cast" means implicit or explicit cast). 10.1 rule says :
the value of look of integer type shall not implicitly converted different underlying type look complex.
an previous illustration of complex operation : ~u16a
i alter code :
uint16 var1 = 1u; uint16 var2 = (uint16) ~var1;
and obtain warning : think conversion of int negative value unsigned int value not safe. check c99 standard (iso c99) § 6.3.1.3 don't understand if conversion of int unsigned short specified.
in embeddedgurus article read :
c = (unsigned int) a; /* since positive, cast safe */
my questions :
have explicit conversion signed int unsigned short unspecified behavior ? if yes, how utilize complement operator unsigned short in safe way ?
the operands of arithmetic , bitwise operators undergo standard promotions before value computed. shorter int
promoted either int
or unsigned int
, depending on platform (i.e. depending on whether int
can represent values of type that's beingness promoted).
on platform, uint16_t
standard-promoted int
, since int
can represent values of uint16_t
. bitwise negation applied int
value, cause of problem.
to deterministic result independent of platform, convert value unsigned int
yourself:
uint16_t var2 = (uint16_t) ~((unsigned int) var1);
note correct, since unsigned int
required able represent values of uint16_t
.
c casting
No comments:
Post a Comment