简体   繁体   English

C ++我的字节数组到int以及从int到字节数组转换器的问题是什么?

[英]C++ What's wrong with my bytes array to int and int to byte array converters?

i know there is a lot of questions about it, but most of them uses fixed sized converters, like 4 bytes to int and etc. 我知道有很多问题,但是大多数使用固定大小的转换器,例如4字节到int等。
I have an templated functions to convert bytes to numbers and etc, but have a problem :D 我有一个模板函数将字节转换为数字等,但是有一个问题:D

template <typename IntegerType>
     static IntegerType bitsToInt(BYTE* bits, bool little_endian = true)
     {
         IntegerType result = 0;

         if (little_endian)
             for (int n = sizeof(IntegerType); n >= 0; n--)
                 result = (result << 8) + bits[n];
         else
             for (int n = 0; n < sizeof(IntegerType); n++)
                 result = (result << 8) + bits[n];

         return result;
     }

     template <typename IntegerType>
     static BYTE *intToBits(IntegerType value)
     {
         BYTE result[sizeof(IntegerType)] = { 0 };

         for (int i = 0; i < sizeof(IntegerType); i++)
             result = (value >> (i * 8));

         return result;
     }

     static void TestConverters()
     {
         short int test = 12345;

         BYTE *bytes = intToBits<short int>(test);

         short int test2 = bitsToInt<short int>(bytes); //<--i getting here different number, then 12345, so something goes wrong at conversion
     }

So, could anyone say what's wrong here? 所以,有人可以说这是怎么回事吗?

static BYTE *intToBits(IntegerType value)

这将返回一个指向本地分配的内存的指针,一旦函数返回,该指针将超出范围,并且不再有效。

There are several bugs in the function intsToBits 1. Insted of 函数intsToBits 1中有几个错误。

result = (value >> (i * 8)); 

there should be 应该有

result[i] = 0xFF & (value >> (i * 8)); 

More serious one you return the pointer to the memory on the stack, which is generally incorrect after you exit the function. 更严重的是,您将指针返回到堆栈上的内存,通常在退出函数后不正确。 You shoul allocate the memory with the new operator. 您应该使用new运算符分配内存。

BYTE * result = new BYTE[sizeof(IntegerType)];

The you'll be needed to release the memory 您将需要释放内存

这可能不是您唯一的问题,但是intToBits返回了一个指向局部变量的指针,该变量是未定义的行为。

尝试使用new分配返回的字节数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM