c# – 如果数据未在给定的偏移处对齐,为什么BitConverter.ToInt32一次读取一个字节?

c# – 如果数据未在给定的偏移处对齐,为什么BitConverter.ToInt32一次读取一个字节?,第1张

概述很抱歉这个令人困惑的标题,但我想不出更好的解释方法. 最近浏览the source code的BitConverter时,我遇到了一段奇怪的代码: public static unsafe int ToInt32(byte[] value, int startIndex){ fixed (byte* pbyte = &value[startIndex]) { if 很抱歉这个令人困惑的标题,但我想不出更好的解释方法.

最近浏览the source code的BitConverter时,我遇到了一段奇怪的代码:

public static unsafe int ToInt32(byte[] value,int startIndex){    fixed (byte* pbyte = &value[startIndex])    {        if (startIndex % 4 == 0) // data is aligned             return *((int*)pbyte);        else        {             if (IslittleEndian)            {                  return (*pbyte) | (*(pbyte + 1) << 8)  | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24);             }             else            {                 return (*pbyte << 24) | (*(pbyte + 1) << 16)  | (*(pbyte + 2) << 8) | (*(pbyte + 3));                                     }         }    }}

在这种情况下,如何将pbyte转换为int *(第6行)会违反数据对齐?为了简洁,我把它留了下来,但代码有正确的参数验证,所以我很确定它不能是内存访问违规.铸造时会失去精度吗?

换句话说,为什么不能将代码简化为:

public static unsafe int ToInt32(byte[] value,int startIndex){    fixed (byte* pbyte = &value[startIndex])    {        return *(int*)pbyte;    }}

编辑:Here是有问题的代码部分.

解决方法 我敢打赌,这与C#规范5.0版本中的§18.4的这一部分有关(强调我的):

When one pointer type is converted to another,if the resulting pointer is not correctly aligned for the pointed-to type,the behavior is undefined if the result is dereferenced.

在“未对齐”的情况下进行字节复制是为了避免依赖于明确未定义的行为.

@H_404_43@ 总结

以上是内存溢出为你收集整理的c# – 如果数据未在给定偏移处对齐,为什么BitConverter.ToInt32一次读取一个字节?全部内容,希望文章能够帮你解决c# – 如果数据未在给定的偏移处对齐,为什么BitConverter.ToInt32一次读取一个字节?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1231593.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存