如何处理“字节序" [英] How to deal with 'Endianness'

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

问题描述

我仍在研究运行正常的ICMP侦听器,并对如何处理字节序"感到困惑.我的第一种方法是将数据从缓冲区移到适当的(初始为数组)字段(uint等)中,然后反转字节顺序,然后再将数据传递给适当的BitConverter成员.虽然可以,但不是很优雅.

I’m still working on a properly functioning ICMP listener and puzzling how to deal with ‘endianness’. My first approach was getting the data out of the buffer into an appropriate (array initially) field (uint etc.) and then reversing the byte order, before passing the data on to the appropriate BitConverter member. Though it works, it is not very elegant.

第二种方法是准备由二维数组驱动的整个缓冲区,其中包含需要调整的字段的位置和长度.这也行得通,其优点是现有代码无需更改,但是(严重)缺乏可读性.

Second approach was to prepare the entire buffer driven by a two dimensional array, containing the position and length of fields, that need to be adjusted. That works too, with an added advantage that existing code needs no changes, but it lacks (severely) in readability.

我正在努力了解当今可用的新编程环境(特别是.Net和C#),并且令我感到非常惊讶的是,1975年以来存在的问题仍未得到适当处理.我有第一批针对(IBM)PC开发的(ISA)网卡(针对以太网1.0,基于Motorola 68000 CPU),我清楚地记得其中涉及的问题;不仅是多字库类型,而且所有数据都位于不同的"endiannnes"(然后是16位字)中,有效地消除了"DMA"数据的可能性.

I am making an effort to understand the new programming environments available today (specifically .Net and C#), and I am very surprised that issues that existed back in 1975 are still not appropriately dealt with. I had one of the first (ISA) network cards (targeted for Ethernet 1.0 and based on a Motorola 68000 CPU) developed for a (IBM) PC and I clearly remember the issues involved; not just multi word base types, but all data was in different ‘endiannnes’ (then 16 bit words), effectively killing the possibility to ‘DMA’ data.

在网络适配器播放的过程中,我认为这是非常小的工作,可以调整适合其环境的数据,但是用这种方法解决它似乎不是太大的问题.(?)

I would consider it to be a very small effort on the part that a network adapter plays, to adjust data appropriate to its environment, but it seems to be not too big an issue to resolve it that way. (?)

底线;我不敢相信我是唯一负担此事的人,我衷心希望有人能提出比我现在使用的解决方案更好的解决方案.

Bottom line; I can’t believe that I’m the only one burdened with this and I sincerely hope that someone has come up with a better solution than the ones I’m using now.

(此文本是借助Google翻译(如我所说的荷兰语)翻译的)

(this text it translated with the help of Google translate (as I’m Dutch))

推荐答案

简单;如果Endianness成为问题的可能性很小,请不要使用BitConverter(对于.NET,这主要意味着在某些硬件上具有独占性" AFAIK).乔恩·斯凯特(Jon Skeet)在"MiscUtil"中有一个EndianBitConverter,可能会有所帮助;否则,只需通过移位等方式进行编码即可.

Simply; dont use BitConverter if there is a remote chance of Endianness being an issue (which for .NET mainly means "mono on some hardware" AFAIK). Jon Skeet has an EndianBitConverter in "MiscUtil" that may help; otherwise just do the encoding via bit-shifting etc.

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

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