基本上我正在阅读一种二进制格式,其中 4 个字节指定要遵循的字符串的大小。所以我想将我从缓冲区读取的 4 个字符转换为 1 个整数。
这是我所拥有的。
int FileReader::getObjectSizeForMarker(int cursor, int eof, char * buffer) {
//skip the marker and read next 4 byes
int cursor = cursor + 4; //skip marker and read 4
char tmpbuffer[4] = {buffer[cursor], buffer[cursor+1], buffer[cursor+2], buffer[cursor+3]};
int32_t objSize = tmpbuffer;
return objSize;
}
Run Code Online (Sandbox Code Playgroud)
想法?
手动解包很容易:
unsigned char *ptr = (unsigned char *)(buffer + cursor);
// unpack big-endian order
int32_t objSize = (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3];
Run Code Online (Sandbox Code Playgroud)