utility to write unsigned shorts
This commit is contained in:
17
core/src/main/groovy/com/muwire/core/util/DataUtil.groovy
Normal file
17
core/src/main/groovy/com/muwire/core/util/DataUtil.groovy
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
package com.muwire.core.util
|
||||||
|
|
||||||
|
class DataUtil {
|
||||||
|
|
||||||
|
private static int MAX_SHORT = (0x1 << 16) - 1
|
||||||
|
|
||||||
|
static writeUnsignedShort(int value, OutputStream os) {
|
||||||
|
if (value > MAX_SHORT || value < 0)
|
||||||
|
throw new IllegalArgumentException("$value invalid")
|
||||||
|
|
||||||
|
byte lsb = (byte) (value & 0xFF)
|
||||||
|
byte msb = (byte) (value >> 8)
|
||||||
|
|
||||||
|
os.write(msb)
|
||||||
|
os.write(lsb)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package com.muwire.core.util
|
||||||
|
|
||||||
|
import static org.junit.Assert.fail
|
||||||
|
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class DataUtilTest {
|
||||||
|
|
||||||
|
|
||||||
|
private static void usVal(int value) {
|
||||||
|
ByteArrayOutputStream baos = new ByteArrayOutputStream()
|
||||||
|
DataUtil.writeUnsignedShort(value, baos)
|
||||||
|
def is = new DataInputStream(new ByteArrayInputStream(baos.toByteArray()))
|
||||||
|
assert is.readUnsignedShort() == value
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
void testUnsignedShort() {
|
||||||
|
usVal(0)
|
||||||
|
usVal(20)
|
||||||
|
usVal(Short.MAX_VALUE)
|
||||||
|
usVal(Short.MAX_VALUE + 1)
|
||||||
|
usVal(0xFFFF)
|
||||||
|
|
||||||
|
try {
|
||||||
|
usVal(0xFFFF + 1)
|
||||||
|
fail()
|
||||||
|
} catch (IllegalArgumentException expected) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user