我知道有很多关于它的问题,但其中大多数使用固定大小的转换器,如4个字节到int等。
我有一个模板化的函数将字节转换为数字等,但有一个问题: D
C++我的字节数组到int和int到字节数组转换器有什么问题?
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
}
那么,有人能说这里有什么问题吗?
我还没有检查整个事情,但对于(int n = sizeof(IntegerType); n> = 0; n--) 应该可能读为(int n = sizeof(IntegerType)-1; n > = 0; n--) – Hybrid 2012-02-16 13:30:08
你使用什么编译器? 'result =(value >>(i * 8));'不应该编译。你也应该尝试启用警告...... – PlasmaHH 2012-02-16 13:31:56
intToBits是如何编译的,当它试图给常量指针'result'赋值一个新值时?不应该是结果[i] = ...? – Hybrid 2012-02-16 13:33:31