T
techie
I have defined a number of unsigned integer types as follows:
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint32;
typedfe long long uint64;
Is it necessary to explicitly cast from one type of unsigned integer type to
another even though they do so implicitly?
e.g. bytes0_1 |= (static_cast<uint16>(VersionNo)) << 12;
bytes0_1 is of type uint16. Here I thought it is safer to cast VersionNo
(type uint8) to uint16 before I do a left shift. I was just a bit worried
about shifting the digits off the end of an 8 bit number. Likewise in the
statement below I cast the result of the left shift and bit wise addition to
uint64.
byte6 = static_cast<uint8>((MAC_Adddress >> 40) & 0xFF);
MAC_Adddress is of type uint64.
When I run QA C++ (source code analyzer) on my code it issues a few warnings
for the first statement:
Bitwise operator is being applied to a signed type.
This is an implicit conversion between signed and unsigned integer types.
Be aware that an implicit conversion from 'uint16' to 'int' takes place.
I think I can ignore the first two warnings as the types are actually
unsigned integers and not signed as it thinks they are. I think the third
one means that in order to do the left shift it does an implicit conversion
to int as operator << is just defined for int.
Are these static_casts necessary? Is there a better way to write these
statements?
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint32;
typedfe long long uint64;
Is it necessary to explicitly cast from one type of unsigned integer type to
another even though they do so implicitly?
e.g. bytes0_1 |= (static_cast<uint16>(VersionNo)) << 12;
bytes0_1 is of type uint16. Here I thought it is safer to cast VersionNo
(type uint8) to uint16 before I do a left shift. I was just a bit worried
about shifting the digits off the end of an 8 bit number. Likewise in the
statement below I cast the result of the left shift and bit wise addition to
uint64.
byte6 = static_cast<uint8>((MAC_Adddress >> 40) & 0xFF);
MAC_Adddress is of type uint64.
When I run QA C++ (source code analyzer) on my code it issues a few warnings
for the first statement:
Bitwise operator is being applied to a signed type.
This is an implicit conversion between signed and unsigned integer types.
Be aware that an implicit conversion from 'uint16' to 'int' takes place.
I think I can ignore the first two warnings as the types are actually
unsigned integers and not signed as it thinks they are. I think the third
one means that in order to do the left shift it does an implicit conversion
to int as operator << is just defined for int.
Are these static_casts necessary? Is there a better way to write these
statements?