c++ - 将 char 数组转换为整数

标签 c++

基本上我正在读取一种二进制格式,其中 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/

相关文章:

c++ - websocketpp 和 boost.asio 有什么区别?

c++ - Windows/C++ : why are loaded module memory bytes changing at run-time?

c++ - BST的递归插入

c++ - vector 和许多索引

c++ - 在自定义硬件上映射内存

不同类型的 C++ 映射赋值重载

c++ - 为什么要在 eclipse 中使用 Cmake

c++ - SFML - 将 RenderTexture 保存到图像 0xC0000005 时访问冲突读取位置

c++ - 无法测量 Windows 下由 std::vector<>::reserve 引起的内存分配

c++ - 使用 Boost.Lockfree 队列比使用互斥锁慢