c++ - 在内存映射文件中交换字节的有效方法

标签 c++ endianness memory-mapped-files

我通过使用下面显示的函数将数据 block 读入内存并交换大端整数,设法解析了一个大型二进制文件 (~8Gb)。但是,我试图通过使用 Boost Memory-Mapped files 获得更多性能。但我无法使用 endian_swap 函数,因为该文件是以只读模式打开的。有什么有效的方法可以在不写入原始文件的情况下交换字节吗?如果不是,性能会受到 I/O 开销的影响吗?

inline void endian_swap(unsigned short int& x)
{
  x = (x>>8) |
    (x<<8);
}
inline void endian_swap(unsigned int& x)
{
  x = (x>>24) |
    ((x<<8) & 0x00FF0000) |
    ((x>>8) & 0x0000FF00) |
    (x<<24);
}
inline void endian_swap(unsigned long long int& x)
{
  x = (((unsigned long long int)(x) << 56) | \
      (((unsigned long long int)(x) << 40) & 0xff000000000000ULL) | \
      (((unsigned long long int)(x) << 24) & 0xff0000000000ULL) | \
      (((unsigned long long int)(x) << 8)  & 0xff00000000ULL) | \
      (((unsigned long long int)(x) >> 8)  & 0xff000000ULL) | \
      (((unsigned long long int)(x) >> 24) & 0xff0000ULL) | \
      (((unsigned long long int)(x) >> 40) & 0xff00ULL) | \
      ((unsigned long long int)(x)  >> 56));
}

代码是在这个 article 上找到的. 非常感谢您的宝贵时间

最佳答案

至少底层操作系统支持你想要的行为:

   MAP_PRIVATE
              Create a private copy-on-write mapping.  Updates
              to the mapping are not visible to other processes
              mapping the same file, and are not carried through
              to the underlying file.  It is unspecified whether
              changes made to the file after the mmap() call are
              visible in the mapped region.

priv 标志似乎转换为 MAP_PRIVATE:

void* data = 
    ::BOOST_IOSTREAMS_FD_MMAP( 
        const_cast<char*>(p.hint), 
        size_,
        readonly ? PROT_READ : (PROT_READ | PROT_WRITE),
        priv ? MAP_PRIVATE : MAP_SHARED,
        handle_, 
        p.offset );
if (data == MAP_FAILED)
    cleanup_and_throw("failed mapping file");

关于c++ - 在内存映射文件中交换字节的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6560539/

相关文章:

ipv6 - 如何更改 IPV6 地址的字节顺序(从网络到主机,反之亦然)?

c++ - 在C++中,接受基类的构造函数算作复制构造函数吗?

c++ - 体素世界中的碰撞检测

c++ - 什么会导致我的数据包的字节顺序变得部分困惑?

windows - 如何防止将在 Windows 临时关闭时删除文件上打开的内存映射刷新到磁盘

Java nio : How to read characters from memory mapped file with correct charset

c++ - 第二次内存映射文件但大小更大是否符合犹太洁食标准?

c++ - 丢弃 volatile 安全吗?

c++ - 如何通过在OnEraseBkgnd()中使用StretchBlt制作缩小位图的动画并摆脱其周围的 “shadow”? (MFC)

java - 通过AudioInputStream读取数据需要关心big endian和little endian吗?