How can I store 4 8 bit coordinates into one integer (C#)?

后端 未结 4 1018
面向向阳花
面向向阳花 2021-01-28 11:27

Lets say I have the following four variables: player1X, player1Y, player2X, player2Y. These have, for example, respectively the following values: 5, 10, 20, 12. Each of these va

相关标签:
4条回答
  • 2021-01-28 11:56

    To "squeeze" 4 8 bits value in a 32 bit space, you need to "shift" the bits for your various values, and add them together.

    The opposite operations is to "unshift" and use some modulo to get the individual numbers you need.

    0 讨论(0)
  • 2021-01-28 11:59

    You can place the values by shifting to the apropriate offset

    Example:

    // Composing
    byte x1 = ...;
    byte x2 = ...;
    byte x3 = ...;
    byte x4 = ...;
    
    uint x = x1 | (x2 << 0x8) | (x3 << 0x10) | (x4 << 0x18);
    
    // Decomposing
    uint x = ...;
    
    byte x1 = x & 0xFF;
    byte x2 = (x >> 0x8) & 0xFF;
    byte x3 = (x >> 0x10) & 0xFF;
    byte x4 = (x >> 0x18) & 0xFF;
    
    0 讨论(0)
  • 2021-01-28 12:16

    You can use BitConverter

    To get one Integer out of 4 bytes:

    int i = BitConverter.ToInt32(new byte[] { player1X, player1Y, player2X, player2Y }, 0);
    

    To get the four bytes out of the integer:

    byte[] fourBytes = BitConverter.GetBytes(i);
    
    0 讨论(0)
  • 2021-01-28 12:18

    Here is an alterantive:

    Make a struct with defined packing. Expose:

    • The int32 and all 4 bytes at the same time
    • Make sure the apcking overlaps (i.e. int starts at 0, byte variables at 0, 1,2,3

    Done.

    And you can easily access and work with them WITHOUT a bitconverter et al and never have to define an array, which is expensive jsut to throw it away.

    0 讨论(0)
提交回复
热议问题