Question

I am currently developing a C# 2D sandbox based game. The game world is filled with tiles/blocks. Since the world is so large the game can sometimes use more than what is allowed for 32-bit application.

My tiles consist of the following data inside a struct:

    public byte type;
    public byte typeWall;
    public byte liquid;
    public byte typeLiquid;
    public byte frameX;
    public byte frameY;
    public byte frameWallX;
    public byte frameWallY;

I am looking to encapsulate all this data within one "long" (64-bit integer).

I want properties to get and set each piece of data using bit shifting, etc... (I have never done this).

Would this save space? Would it increase processing speed? If so how can it be accomplished?

Thanks.

Was it helpful?

Solution

I am looking to encapsulate all this data within one "long" (64-bit integer).

You can use StructLayoutAttribute with LayoutKind.Explicit and then decorate fields with FieldOffsetAttribute specifying the exact position.

I want properties to get and set each piece of data using bit shifting, etc... (I have never done this).

Then use shift left (<<), shift right (>>) and masking (and && to extract / or || to write (don't forget about any non-zero bits in the target byte)) with 0xff to separate individual bytes. Read more about bitwise operations here.

Would this save space? Would it increase processing speed?

Did you measure it? Did you discover a performace / memory consuption problem? If yes, go optimize it. If not, do not do premature optimizations. In other words, don't blindly try without measuring first.

OTHER TIPS

I don't know why you want to do this, but you can do it in this way:

byte type = 4;
byte typeWall = 45;
byte liquid = 45;
byte typeLiquid = 234;
byte frameX = 23;
byte frameY = 23;
byte frameWallX = 22;
byte frameWallY = 221;

byte[] bytes = new [] {type, typeWall, liquid, typeLiquid, frameX, frameY, frameWallX, frameWallY};

BitConverter.ToInt64(bytes, 0);

or using << (shift) operator.

As you can see by pasting the following code into linqpad :

void Main()
{
    sizeof(byte).Dump("byte size");
    sizeof(Int32).Dump("int 32");
    sizeof(Int64).Dump("int 64");
    sizeof(char).Dump("for good measure, a char:");
}

You'll get:

byte size   1 
int 32      4 
int 64      8 
for good measure, a char: 2 

So packing 8 bytes in an int64 will be the same, but you'll have to play with the bits yourself (if that's your thing, by all means, go for it :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top