3 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
5 * This program and the accompanying materials are made available under the
6 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7 * and is available at http://www.eclipse.org/legal/epl-v10.html
10 package org.openflow.util;
12 import java.math.BigInteger;
13 import java.nio.ByteBuffer;
15 import junit.framework.TestCase;
17 public class UnsignedTest extends TestCase {
18 public static String ULONG_MAX = "18446744073709551615";
21 * Tests that we correctly extract an unsigned long into a BigInteger
24 public void testGetUnsignedLong() throws Exception {
25 ByteBuffer bb = ByteBuffer.allocate(8);
26 bb.put((byte)0xff).put((byte)0xff).put((byte)0xff).put((byte)0xff);
27 bb.put((byte)0xff).put((byte)0xff).put((byte)0xff).put((byte)0xff);
30 BigInteger bi = Unsigned.getUnsignedLong(bb);
31 BigInteger uLongMax = new BigInteger(ULONG_MAX);
32 for (int i = 0; i < uLongMax.bitCount(); ++i) {
33 TestCase.assertTrue("Bit: " + i + " should be: " + uLongMax.testBit(i),
34 uLongMax.testBit(i) == bi.testBit(i));
36 TestCase.assertEquals(ULONG_MAX, bi.toString());
38 bb = ByteBuffer.allocate(10);
40 bb.put((byte)0xff).put((byte)0xff).put((byte)0xff).put((byte)0xff);
41 bb.put((byte)0xff).put((byte)0xff).put((byte)0xff).put((byte)0xff);
45 bi = Unsigned.getUnsignedLong(bb, 1);
46 uLongMax = new BigInteger(ULONG_MAX);
47 for (int i = 0; i < uLongMax.bitCount(); ++i) {
48 TestCase.assertTrue("Bit: " + i + " should be: " + uLongMax.testBit(i),
49 uLongMax.testBit(i) == bi.testBit(i));
51 TestCase.assertEquals(ULONG_MAX, bi.toString());
55 * Tests that we correctly put an unsigned long into a ByteBuffer
58 public void testPutUnsignedLong() throws Exception {
59 ByteBuffer bb = ByteBuffer.allocate(8);
60 BigInteger uLongMax = new BigInteger(ULONG_MAX);
61 Unsigned.putUnsignedLong(bb, uLongMax);
62 for (int i = 0; i < 8; ++i) {
63 TestCase.assertTrue("Byte: " + i + " should be 0xff, was: " + bb.get(i),
64 (bb.get(i) & (short)0xff) == 0xff);
67 bb = ByteBuffer.allocate(10);
68 Unsigned.putUnsignedLong(bb, uLongMax, 1);
70 for (int i = 0; i < 8; ++i) {
71 TestCase.assertTrue("Byte: " + i + " should be 0xff, was: " +
72 bb.get(offset+i), (bb.get(offset+i) & (short)0xff) == 0xff);