加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如果数据未在给定的偏移处对齐,为什么BitConverter.ToInt3

发布时间:2020-12-15 22:19:07 所属栏目:百科 来源:网络整理
导读:很抱歉这个令人困惑的标题,但我想不出更好的解释方法. 最近浏览the source code的BitConverter时,我遇到了一段奇怪的代码: public static unsafe int ToInt32(byte[] value,int startIndex){ fixed (byte* pbyte = value[startIndex]) { if (startIndex % 4
很抱歉这个令人困惑的标题,但我想不出更好的解释方法.

最近浏览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.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读