修复循环变量的-Wconversion GCC警告

时间:2015-07-22 13:19:25

标签: c++ c++11 gcc warnings gcc-warning

我想在现有代码中修复编译器警告,并遇到以下自由函数:

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);
}

TODO评论下方的行引发了以下GCC v4.7.1警告:

warning: conversion to 'unsigned char' from 'int' may alter its value [-Wconversion]

如何重构该代码,以避免出现警告?我无法在循环中用unsigned char替换int,因为这会改变行为。

1 个答案:

答案 0 :(得分:3)

您可以将j <<= 1替换为

 j = static_cast<unsigned char> (j << 1)

或者甚至

 j = static_cast<unsigned char> ((j << 1)&UCHAR_MAX)

然而,我觉得你的代码无论如何都不太可读......也许你可能会发表一些评论......