As a workaround for warning C4333 ('>>': right shift too large, data loss)

I have the following function to convert an integer of arbitrary size to a buffer:

template<typename T>
std::string build_data_from(T val)
{
  std::string result;

  for (int i = 0; i < sizeof(val); i++)
  {
    result.insert(0, 1, char(val));
    val = val >> 8;
  }

  return result;
};

However, when calling the template function with unsigned char, a warning is issued in Visual C ++ 2008:

std::string x(build_data_from<unsigned char>(1));

warning C4333: '→': right shift by too large amount, data loss

Is there any clean way (without using the pragma warning directive) to get around this?

+3
source share
3 answers

Pretty simple: overload build_data_fromfor unsigned char(s char).

, std::enable_if, , :

std::string build_data_from(char val)
{
  std::string result; result += val; return result;
}

std::string build_data_from(unsigned char val)
{
  return build_data_from(char(val));
}

, unsigned char char ? ( , unsigned char , )

+2

.

val = val >> 8;

to

val = val >> 7 >> 1;

val = (val >> 7 >> 1) & 0xff;
+3

if:

template<typename T>
std::string build_data_from(T val)
{
  std::string result;

  for (size_t i = 0; i < sizeof(val); i++)
  {
    result.insert(0, 1, char(val));
    if (sizeof (T) > 1)
      val = val >> 8;
  }

  return result;
}

if (sizeof(T) > 1) T, , . , T char, , .

Btw: you should declare your variable ias size_t, rather than int. the result sizeof()is equal size_t, and some compilers (e.g. gcc) warn you if you are doing a comparison between unsigned integers.

+2
source

Source: https://habr.com/ru/post/1791001/


All Articles