bunti/src/main/java/de/ctdo/bunti/artnet/ByteUtils.java

81 lines
2.4 KiB
Java
Raw Normal View History

2012-02-25 15:55:47 +00:00
/*
* This file is part of artnet4j.
*
* Copyright 2009 Karsten Schmidt (PostSpectacular Ltd.)
*
* artnet4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* artnet4j is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with artnet4j. If not, see <http://www.gnu.org/licenses/>.
*/
package de.ctdo.bunti.artnet;
2012-02-25 15:55:47 +00:00
public class ByteUtils {
2012-03-08 00:22:31 +00:00
private static final int BYTE_OVERFLOW = 256;
private static final int BYTE_MAX = 0xff;
private static final int BIT_PER_BYTE = 8;
private static final int ONE_BYTE_OFFSET = 1;
2012-03-04 09:50:50 +00:00
private final byte[] data;
2012-03-07 23:04:03 +00:00
public ByteUtils(byte[] data) {
2012-03-10 21:20:57 +00:00
this.data = data.clone();
}
public static int byteToUint(byte b) {
2012-03-08 00:22:31 +00:00
return (b < 0 ? BYTE_OVERFLOW + b : b);
2012-03-07 23:57:50 +00:00
}
public static byte uintToByte(int i) {
2012-03-08 00:22:31 +00:00
return (byte)(i & BYTE_MAX);
}
2012-03-07 23:57:50 +00:00
2012-03-04 09:50:50 +00:00
public final byte[] getBytes() {
2012-03-10 21:20:57 +00:00
return data.clone();
2012-02-25 15:55:47 +00:00
}
2012-03-07 23:57:50 +00:00
public final int getInt16(int offset) {
2012-03-08 00:22:31 +00:00
return (byteToUint(data[offset]) << BIT_PER_BYTE) | byteToUint(data[offset + 1]);
2012-03-07 23:57:50 +00:00
}
public final int getInt16LE(int offset) {
2012-03-08 00:22:31 +00:00
return (byteToUint(data[offset + ONE_BYTE_OFFSET]) << BIT_PER_BYTE) | byteToUint(data[offset]);
2012-03-07 23:57:50 +00:00
}
public final int getInt8(int offset) {
return byteToUint(data[offset]);
}
2012-02-25 15:55:47 +00:00
public final int getLength() {
return data.length;
}
public final void setByteChunk(byte[] buffer, int offset, int len) {
System.arraycopy(buffer, 0, data, offset, len);
}
public final void setInt16(int val, int offset) {
2012-03-08 00:22:31 +00:00
data[offset] = (byte) (val >> BIT_PER_BYTE & BYTE_MAX);
data[offset + ONE_BYTE_OFFSET] = (byte) (val & BYTE_MAX);
2012-02-25 15:55:47 +00:00
}
public final void setInt16LE(int val, int offset) {
2012-03-08 00:22:31 +00:00
data[offset] = (byte) (val & BYTE_MAX);
data[offset + ONE_BYTE_OFFSET] = (byte) (val >> BIT_PER_BYTE & BYTE_MAX);
2012-02-25 15:55:47 +00:00
}
public final void setInt8(int val, int offset) {
2012-03-08 00:22:31 +00:00
data[offset] = (byte) (val & BYTE_MAX);
2012-02-25 15:55:47 +00:00
}
}