根据奇怪的协议将整数转换为字节数组

时间:2014-08-19 19:00:39

标签: java bytearray minecraft bukkit

我正在构建一个字节数组,其中包含有关已更改的块的数据。

我有整数xyzblockIDblockMeta

Bit mask       Width    Meaning 
00 00 00 0F    4 bits   Block metadata
00 00 FF F0    12 bits  Block ID
00 FF 00 00    8 bits   Y co-ordinate
0F 00 00 00    4 bits   Z co-ordinate, relative to chunk so can fit
F0 00 00 00    4 bits   X co-ordinate, relative to chunk so can fit

如何将整数输入数组?
我可以放心地假设整数将适合'如果这是一个问题。

这是我到目前为止所得到的:

byte[] data = new byte[blocks.length * 4];
for (int i = 0; i < blocks.length; i++) {
    int j = i * 4;
    int blockX = blocks[i].getBlockX() - (chunk.getX() * 16);
    int blockY = blocks[i].getBlockY();
    int blockZ = blocks[i].getBlockZ() - (chunk.getZ() * 16);
    int blockID = material.getId();
    int blockMeta = 0;
    // data[j] = // Help!
    // data[j + 1] = //Help!

    // data[j + 2] = //Help!
    // data[j + 3] = //Help!
}

3 个答案:

答案 0 :(得分:1)

这应该可以解决问题。

byte[] finalMessage = ByteBuffer.allocate(4).putInt( (blockX << 28) | (blockZ << 24) | (blockY << 16) | (blockID << 4) | blockMeta ).array();

答案 1 :(得分:1)

试试这个:

    int[] data = new int[blocks.length];
for (int i = 0; i < blocks.length; i ++) {
    int blockX = blocks[i].getBlockX() << 28;
    int blockY = blocks[i].getBlockY() << 16;
    int blockZ = blocks[i].getBlockZ() << 24;
    int blockID = material.getId() << 4;
    int blockMeta = 0;
    int result = blockX | blockY | blockZ | blockID | blockMeta;
    data[i] = result;
}

如果你真的需要字节:

    byte[] data = new byte[blocks.length*4];
for (int i = 0; i < blocks.length; i ++) {

    byte byte0 = material.getId() << 4 | blockMeta;
    byte byte1 = blockMeta >> 4;
    byte byte2 = blocks[i].getBlockY();
    byte byte3 = blocks[i].getBlockZ() | (blocks[i].getBlockX() >> 4);
    data[4*i] = byte0;
    data[4*i + 1] = byte1;
    data[4*i + 2] = byte2;
    data[4*i + 3] = byte3;
}

答案 2 :(得分:0)

试试这个:

byte[] finalMessage = ByteBuffer.allocate(20).putInt(x).putInt(y).putInt(z).putInt(blockID).putInt(blockMeta).array();