让我说我有8个unsigned char,我想转换为unsigned long long。
例如,如果所有char都等于0xFF,则无符号long long将等于0xFFFFFFFFFFFFFFFF。使用C或C ++最有效的方法是什么?
答案 0 :(得分:4)
例如:
unsigned char buffer[8] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
unsigned long long target;
memcpy(&target, buffer, sizeof target);
请注意,如果buffer
的所有元素都不具有相同的值,则结果将取决于字节顺序(little-endian与big-endian)。
这也假设unsigned long long
正好是8个字节。这种情况非常普遍,但并不能保证。 (它也不能保证一个字节正好是8位;它可以更多。unsigned char
定义为1字节。)
答案 1 :(得分:4)
您可以直接分配位
,而不是memcpy unsigned char buffer[8] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
unsigned long long l = 0;
for (int i = 0; i < 8; ++i) {
l = l | ((unsigned long long)buffer[i] << (8 * i));
}
我相信这对字节序不敏感。
答案 2 :(得分:0)
对不起我最初的愚蠢回答,真的应该更仔细地阅读这个问题。希望这个更有帮助。转换的方式取决于字节数组中长long表示的字节顺序是否与您正在处理的体系结构的字节顺序相同。
C ++:
#include <iostream>
#include <cstring>
using namespace std;
// Assuming ca is at least 8 bytes, the size of long long, interpret the
// first 8 bytes as long long.
// differentEndian == true means the endianness of the machine is
// different from the representation in ca.
long long getLongLong( unsigned char * ca, bool differentEndian )
{
long long retVal;
if (differentEndian)
{
for (int i = 0; i < 4; i++)
{
unsigned char _tmpCh = ca[i];
ca[i] = ca[7-i];
ca[7-i] = _tmpCh;
}
}
retVal = *reinterpret_cast<unsigned long long *>(ca);
return retVal;
}
int main()
{
unsigned char cArray[] = {0xff, 0x1, 0x70, 0x2, 0x61, 0x3, 0x52, 0x4};
unsigned long long ll = getLongLong( cArray, false );
cout << "Result for same endian: " << hex << ll << " or " << dec << ll << endl;
ll = getLongLong( cArray, true );
cout << "Result for different endian: " << hex << ll << " or " << dec << ll << endl;
return 0;
}
C:
#include <stdio.h>
#include <string.h>
// Assuming ca is at least 8 bytes, the size of long long, interpret the
// first 8 bytes as long long.
// differentEndian != 0 means the endianness of the machine is
// different from the representation in ca.
long long getLongLong( unsigned char * ca, int differentEndian )
{
long long retVal;
if (differentEndian)
{
int i;
for (i = 0; i < 4; i++)
{
unsigned char _tmpCh = ca[i];
ca[i] = ca[7-i];
ca[7-i] = _tmpCh;
}
}
memcpy( &retVal, ca, sizeof(long long));
return retVal;
}
int main()
{
unsigned char cArray[] = {0xff, 0x1, 0x70, 0x2, 0x61, 0x3, 0x52, 0x4};
unsigned long long ll = getLongLong( cArray, 0 );
printf("Result for same endian: %llx or %llu\n", ll, ll);
ll = getLongLong( cArray, 1 );
printf("Result for different endian: %llx or %llu\n", ll, ll);
return 0;
}
两个版本的输出是:
Result for same endian: 4520361027001ff or 311315039429591551
Result for different endian: ff01700261035204 or 1837509111016818739