我已经编写了一个测试,试图找出char[]
数组和long long
之间的转换是如何工作的。部分由于我自己的理解,我试图找出这样做的按位方法。
从概念上讲,对于long long
到char[]
,下面的感觉是正确的。我向左移动,然后向右移动以限制向右:
for (int i = 0; i < BUFFER_SIZE; i++)
{
buffer[i] = ((value >> (8 * i)) & 0XFF);
}
要转换回来,向左移动并对缓冲区求和:
long long recoveredValue = 0;
for (int i = 0; i < BUFFER_SIZE; i++)
{
auto byteVal = ((buffer[i]) << (8 * i));
recoveredValue = recoveredValue + byteVal;
}
以下是我的整个测试计划。似乎当我填写上面的第一步(在IntToByteArray
中)时,buffer[0]
的值在`buffer [32]&#39;处重复。我知道这里有一个问题,但我无法弄明白。
请注意,对于我的应用,我的BUFFER_SIZE
为63,我的long long
将限制在2 ^ 63以下。另外,如果我将BUFFER_SIZE
限制在32以下,则可行。我错过了一个关于64位int的子句我不是吗?但是在哪里,&amp;如何?
// Test_BitConversion.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <cmath>
#define BUFFER_SIZE 64
unsigned char buffer[BUFFER_SIZE] = { 0 }; // This is the buffer I have available
// useful alternative method for checking conversion
// can't use in production, because I'm moving between C++ & C#
union byteunion
{
long long value;
unsigned char arr[BUFFER_SIZE];
};
// Convert long long to byte array
void IntToByteArray(long long value)
{
for (int i = 0; i < BUFFER_SIZE; i++)
{
buffer[i] = ((value >> (8 * i)) & 0XFF);
}
}
// Convert byte array to long long
long long ByteArrayToInt()
{
long long recoveredValue = 0;
for (int i = 0; i < BUFFER_SIZE; i++)
{
auto byteVal = ((buffer[i]) << (8 * i));
recoveredValue = recoveredValue + byteVal;
}
return recoveredValue;
}
// Test union can convert value both directions
bool TestUnion(long long value)
{
byteunion originalUnion, recoveredUnion;
originalUnion.value = value;
for (int a = 0; a < BUFFER_SIZE; a++)
{
recoveredUnion.arr[a] = originalUnion.arr[a];
}
if (recoveredUnion.value != value)
{
printf("Union value failed");
return false;
}
return true;
}
int main()
{
long long originalValue = 2004293008363;
originalValue = (long long)std::pow(2, 31);
long long recoveredValue = 0;
byteunion originalUnion;
originalUnion.value = originalValue;
// Loop to find failure point
for (int i = 1; i < BUFFER_SIZE; i++)
{
originalValue = (long long)std::pow(2, i);
// First check Union method
bool unionTest = TestUnion(originalValue);
if (!unionTest)
{
printf("Fail on Union at 2^%i", i);
break; // this is never reached - union method works
}
// convert value to byte array
IntToByteArray(originalValue);
// now convert buffer back to long long
recoveredValue = ByteArrayToInt();
if (originalValue != recoveredValue)
{
printf("Fail recoving at 2^%i\n", i);
break; // this is reached when the original value is 2^31
}
}
printf(" OriginalValue: %llu\n", originalValue);
printf("RecoveredValue: %llu\n", recoveredValue);
system("pause");
return 0;
}
答案 0 :(得分:1)
问题在于将值转换回来。由于整数促销,这个表达式
auto byteVal = ((buffer[i]) << (8 * i));
的类型为int
,而不是long long
。
向buffer[1]
添加演员以解决问题:
auto byteVal = (((long long)buffer[i]) << (8 * i));
虽然使用+
可以正常使用,但在组合值时更常用的方法是使用|
:
recoveredValue |= byteVal;