mmap大字节序与小字节序 [英] mmap big endian vs. little endian

查看:99
本文介绍了mmap大字节序与小字节序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果使用mmap编写uint32_t,是否会遇到大尾数/小尾数约定的问题?特别是,如果我在大字节序的计算机上写一些mmap数据,当我尝试在小字节序的计算机上读取数据时会遇到问题吗?

If I use mmap to write uint32_t's, will I run into issues with big endian/little endian conventions? In particular, if I write some data mmap'ed on a big-endian machine, will I run into issues when I try to read that data on a little-endian machine?

推荐答案

如果您使用的是mmap,则可能会担心速度和效率.您基本上有几种选择.

If you're using mmap, your probably concerned about speed and efficiency. You basically have a few choices.

  1. 使用htonl,htons,ntohl和ntohs函数包装所有读写.在Windows上调用htonl(主机到网络)命令会将数据从小字节序转换为大字节序.在其他体系结构上,这将是一个小问题.这些转换的确有开销,但是取决于您的操作,它们可能是重要的,也可能不是重要的. AFAIK,这是SQLite使用的方法
  2. 您的另一个选择是始终以主机格式写入数据,并在用户需要跨平台迁移数据时提供例程.数据库通常以主机格式读写数据,但是提供了bcp之类的工具,这些工具将以ASCII或网络字节顺序写入.
  3. 您可以使用字节顺序标记来标记文件的标题.程序启动时,它将字节顺序与文件顺序进行比较,并在需要时提供任何翻译.这通常适用于简单的数据格式(例如UTF-16),但不适用于具有多种可变长度类型的格式.

此外,如果执行诸如提供长度前缀或文件偏移之类的操作,则可能混合使用32位和64位指针. 32位平台无法创建大于4GB的mmap视图,因此不太可能支持大于4 GB的文件.诸如rrdtool之类的程序采用这种方法,并在64位平台上支持更大的文件大小.这意味着,如果您在文件中使用平台指针大小,则二进制文件在各个平台之间将不兼容.

Additionally, if you do things like provide length prefixes, or file offsets, you may have a mixture of 32 bit and 64 bit pointers. A 32 bit platform can't create a mmap view larger than 4GB, so it's unlikely that you would support file sizes larger than 4 GB. Programs like rrdtool take this approach, and support much larger file sizes on 64 bit platforms. This means your binary file wouldn't be compatible across platforms if you used the platform pointer size inside of your file.

我的建议是先忽略所有字节顺序问题,并设计系统使其在您的平台上快速运行.如果/当您需要将数据移动到另一个平台时,请选择最简单/最快捷/最合适的方法.如果您开始尝试创建与平台无关的数据格式,则通常会犯错误,并且必须回过头来解决这些错误.当99%的数据是正确的字节顺序,而1%的数据是错误的时,这尤其成问题.这意味着修复数据转换代码中的错误将破坏所有平台上的现有客户端.

My recommendation is to ignore all byte order issues up front, and design the system to run fast on your platform. If/when you need to move your data to another platform, then choose the easiest/quickest/most appropriate method of doing so. If you start out by trying to create a platform independent data format, you will generally make mistakes, and have to go back and fix those mistakes later. This is especially problematic when 99% of the data is in the correct byte order, and 1% of it is wrong. This means fixing bugs in your data translation code will break existing clients on all platforms.

在编写支持多个平台的代码之前,您需要进行多平台测试.

You'll want to have a multi-platform test setup before writing code to support more than one platform.

这篇关于mmap大字节序与小字节序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆