基本上我正在读取一种二进制格式,其中 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;
}
想法?
最佳答案
手动解包非常容易:
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];
关于c++ - 将 char 数组转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12765488/