很抱歉这个令人困惑的标题,但我想不出更好的解释方法.
最近浏览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; } }
解决方法
我敢打赌,这与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.
在“未对齐”的情况下进行字节复制是为了避免依赖于明确未定义的行为.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。