简体   繁体   English

如何获得两个(0〜15)个数字作为属性,以一个字节作为后备字段?

[英]How to get two (0~15) numbers as properties with one byte as backing field?

I'm making a tile based 2d platformer and every byte of memory is precious. 我正在制作基于图块的2d平台程序,并且每个字节的内存都很宝贵。 I have one byte field that can hold values from 0 to 255, but what I need is two properties with values 0~15. 我有一个字节字段,可以保存从0到255的值,但是我需要两个值为0〜15的属性。 How can I turn one byte field into two properties like that? 我如何将一个字节字段变成这样的两个属性?

do you mean just use the lower 4 bits for one value and the upper 4 bits for the other? 您的意思是只将低4位用于一个值,将高4位用于另一个值?

to get two values from 1 byte use... 从1个字节中获取两个值,使用...

a = byte & 15;
b = byte / 16;

setting is just the reverse as 设置只是相反

byte = a | b * 16;

Using the shift operator is better but the compiler optimizers usually do this for you nowadays. 使用shift运算符会更好,但是如今,编译器优化器通常会为您执行此操作。

byte = a | (b << 4);

To piggy back off of sradforth's answer, and to answer your question about properties: 摆脱sradforth的回答,并回答有关属性的问题:

private byte _myByte;
public byte LowerHalf
{
    get
    {
        return (byte)(_myByte & 15);
    }
    set
    {
        _myByte = (byte)(value | UpperHalf * 16);
    }
}
public byte UpperHalf
{
    get
    {
        return (byte)(_myByte / 16);
    }
    set
    {
        _myByte = (byte)(LowerHalf | value * 16);
    }
}

Below are some properties and some backing store, I've tried to write them in a way that makes the logic easy to follow. 以下是一些属性和一些后备存储,我试图以一种易于理解的方式编写它们。

private byte HiAndLo = 0;

private const byte LoMask = 15;  // 00001111
private const byte HiMask = 240; // 11110000

public byte Lo
{
    get
    {
       // ----&&&&
       return (byte)(this.hiAndLo & LoMask);
    }

    set
    {
       if (value > LoMask) // 
       {
           // Values over 15 are too high.
           throw new OverflowException();
       }

       // &&&&0000
       // 0000----
       // ||||||||
       this.hiAndLo = (byte)((this.hiAndLo & HiMask) | value);
    }
}

public byte Hi
{
    get
    {
        // &&&&XXXX >> 0000&&&&
        return (byte)((this.hiAndLo & HiMask) >> 4);
    }

    set
    {
        if (value > LoMask)
        {
            // Values over 15 are too high.
            throw new OverflowException();
        }

        // -------- << ----0000
        //             XXXX&&&&
        //             ||||||||
        this.hiAndLo = (byte)((hiAndLo & LoMask) | (value << 4 )); 
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM