由8位分量重新组合成32位整数



我从文件中读取了4个字符。例如,按照这个顺序读取11110000 00001111 11000011 00111100。我需要将这些从单个字符组合起来,形成一个连续的单个uint32_t 11110000000011111100001100111100。这是一个解决方案,我决定,似乎工作,直到它不工作。

//#include <fstream>
#include <cstdint>
#include <iostream>
//std::fstream File("example", std::ios::binary | std::ios::out | std::ios::in);
char FileDataExpectedResult[4] = {0x00, 0x00, 0x00, 0x0D};
char FileDataUnexpectedResult[4] = {0x00, 0x00, 0x03, 0x64};
uint32_t Reasemble(char* FileDataArray) 
{
uint32_t Result=0x0;

char ComponentByte;
for (int ByteIterator=0; ByteIterator<4; ByteIterator++ ) 
{
//File.read(&ComponentByte, 1);
ComponentByte = FileDataArray[ByteIterator];
uint32_t ExtendedComponentByte = 0x0000 | ComponentByte;
Result = Result | (ExtendedComponentByte << ((32/(ByteIterator+1)-8)));
}
return Result;
}
int main() {

uint32_t Expected = Reasemble(FileDataExpectedResult);
uint32_t Unexpected = Reasemble(FileDataUnexpectedResult);
std::cout << "hopefully 13: " << (int)Expected << "n";
std::cout << "hopefully 868: " << (int)Unexpected << "n";
return 1;
}

此代码将在剥离上下文的更简单的环境中重新创建。当这段代码从文件读取0x0000000D时,它正确地将其转换为13。但是,0x00000364返回108,而不是预期的868。这个想法是一个字节一个字节地读取,然后把它放在一个32位的数字中,并根据它应该在32位数字中的哪个字节来移动它,然后或者用一个单一的32位数字来组合它们。

错误是在((32/(ByteIterator+1)-8))-我敢肯定这不是你想要的。我认为(24 - (ByteIterator*8))是你的目标。

然而,有一些库函数可以处理这类事情(tadman建议使用ntohl)。

最新更新