mirror of https://github.com/zlatinb/muwire
utility to write unsigned shorts
parent
3e02161b7d
commit
e38fc4242b
|
@ -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) {}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue