I want to fix compiler warnings in existing code and came across the following free function:
std::uint16_t calculate_crc16(std::vector<unsigned char> const& kData) {
std::int32_t result{0};
// This nested loop iterates over each bit of the input data.
for (unsigned char const& kByte : kData) {
// TODO(wolters): Refactor to eliminate [-Wconversion] compiler warning.
for (unsigned char j{1}; j; j <<= 1) {
if (((result & 1) ? 1 : 0) ^ ((kByte & j) ? 1 : 0)) {
result >>= 1;
result ^= 0x9299;
} else {
result >>= 1;
}
}
}
return static_cast<std::uint16_t>(result);
}
The line below the TODO
comment raises the following GCC v4.7.1 warning:
warning: conversion to 'unsigned char' from 'int' may alter its value [-Wconversion]
How can I refactor that code, to avoid the warning? I failed replacing unsigned char
with int
in the loop, since that changes the behavior.
You might replace the j <<= 1
with
j = static_cast<unsigned char> (j << 1)
or perhaps even
j = static_cast<unsigned char> ((j << 1)&UCHAR_MAX)
However, I find your code not very readable anyway.... Perhaps you might put some comment...