Auf Thema antworten

Ist es nicht einfacher die Bytes einfach wieder zusammenzusetzen? Das wäre dann auch relativ variabel bezüglich der Anzahl der Bytes.


Also mal zwei Vorschläge:

[code=java]

public static long concatBytes(byte... values) {

    Long result = 0L;

    for (int i = values.length - 1; i >= 0; i--) {

        result <<= Byte.SIZE;

        result |= (-1 >>> (Long.SIZE - Byte.SIZE) & values[i]);

    }

    return result;

}[/code]


Den Rückgabewert müsste man dann immer casten. Also für die ersten 16 Bit auf short etc. zB:

[code=java]

short s = (short) concatBytes((byte) -87, (byte) 0);

System.out.println(s); //169

[/code]

Bei einem int übergibt man entsprechend 4 Bytes und castet auf int.


Noch komfortabler wärs mit einem ByteBuffer:

[code=java]

byte[] array = new byte[]{-87, 0};

ByteBuffer b = ByteBuffer.wrap(array).order(ByteOrder.LITTLE_ENDIAN);

System.out.println(b.getShort()); //169

[/code]


bzw. für ints:

[code=java]

byte[] array = new byte[]{-87, 1, 0,0};

ByteBuffer b = ByteBuffer.wrap(array).order(ByteOrder.LITTLE_ENDIAN);

System.out.println(b.getInt()); //425

[/code]


Hoffe ich hab nichts übersehen :)



Oben