Skip to content

Instantly share code, notes, and snippets.

@oldratlee
Last active December 22, 2015 03:29
Show Gist options
  • Save oldratlee/6410602 to your computer and use it in GitHub Desktop.
Save oldratlee/6410602 to your computer and use it in GitHub Desktop.
import org.junit.Test;
import java.math.BigInteger;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
* @author ding.lid
*/
public class LongStringConvertTest {
@Test
public void test_long() throws Exception {
String input = "7bdf55c4112011e3";
Long result = Long.valueOf(input, 16);
System.out.println(result);
String output = Long.toHexString(result);
System.out.println(output);
assertEquals(input, output);
}
@Test
public void test_long_overflow() throws Exception {
String input = "8bdf55c4112011e3";
try {
Long.valueOf(input, 16);
fail();
} catch (NumberFormatException expected) {
expected.printStackTrace();
}
}
@Test
public void test_unsignedLong() throws Exception {
String input = "8bdf55c4112011e3";
long value = toSignedLong(input);
System.out.println(value);
String output = toUnsignedLongString(value, 16);
System.out.println(output);
assertEquals(input, output);
}
@Test
public void test_unsignedLong_Overflow() throws Exception {
String input = "ffffffffffffffff";
assertEquals(input, toUnsignedLongString(toSignedLong(input), 16));
try {
toSignedLong("10000000000000000");
} catch (IllegalStateException expected) {
expected.printStackTrace();
}
}
private static final BigInteger TWO_64 = BigInteger.ONE.shiftLeft(64);
private static String toUnsignedLongString(long l, int radix) {
BigInteger b = BigInteger.valueOf(l);
if (b.signum() < 0) {
b = b.add(TWO_64);
}
return b.toString(radix);
}
private static long toSignedLong(String hex) {
BigInteger big = new BigInteger(hex, 16);
if (big.compareTo(TWO_64) >= 0) {
throw new IllegalStateException("Big than 2 ^ 63 - 1: " + hex);
}
return big.longValue();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment