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

.net – 如果我有三个可以全部符合32位的单独值,那么使用uint存

发布时间:2020-12-14 01:54:33 所属栏目:Windows 来源:网络整理
导读:我的意思是,说我有一个结构来表示一些数据,它看起来像这样: struct LilStruct{ public readonly short A; public readonly byte B; public readonly byte C; public LilStruct(short a,byte b,byte c) { A = a; B = b; C = c; }} 短的和两个字节的值都可以
我的意思是,说我有一个结构来表示一些数据,它看起来像这样:

struct LilStruct
{
    public readonly short A;
    public readonly byte B;
    public readonly byte C;

    public LilStruct(short a,byte b,byte c)
    {
        A = a;
        B = b;
        C = c;
    }
}

短的和两个字节的值都可以适合32位.我想知道的是(对于对齐目的,性能,等等),如果以下列格式存储这些数据实际上是有意义的:

struct LilStruct
{
    private readonly uint _value;

    public LilStruct(short a,byte c)
    {
        _value = ((uint)a << 16) | ((uint)b << 8) | (uint)c;
    }

    public int A
    {
        get { return (int)(_value >> 16); }
    }

    public int B
    {
        get { return (int)(_value >> 8) & 0x000000FF; }
    }

    public int C
    {
        get { return (int)(_value & 0x000000FF); }
    }
}

这没有意义吗?有什么好处/缺点?

解决方法

在.NET中,当你打算使用结构时,你也可以像这样用 StructLayoutAttribute来装饰结构:

[StructLayout(LayoutKind.Sequential,Pack=1)]
struct LilStruct
{
    public readonly short A;
    public readonly byte B;
    public readonly byte C;

    public LilStruct(short a,byte c)
    {
        A = a;
        B = b;
        C = c;
    }
}

这将具有以下顺序布置字段的效果,例如,字段B将从偏移量16开始.

Pack的值为1表示字段在字节边界处对齐.

(编辑:李大同)

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

    推荐文章
      热点阅读