Skip to content

Instantly share code, notes, and snippets.

@yomik
Created April 6, 2017 08:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yomik/5ae7eb8ce6ea4d1a84d8297eac72f6b1 to your computer and use it in GitHub Desktop.
Save yomik/5ae7eb8ce6ea4d1a84d8297eac72f6b1 to your computer and use it in GitHub Desktop.
UnsignedMath in Java
import java.math.BigInteger;
/**
* Handled unsigned values of primitive types.
*
* Conversion from :
* <ul>
* <li>C uint8_t -> Java short</li>
* <li>C uint16_t -> Java int</li>
* <li>C uint32 -> Java long</li>
* <li>C uint64 -> Java BigInteger</li>
* </ul>
*/
public final class UnsignedMath {
private static final long MAX_UINT32 = Math.abs(2 * (long) Integer.MAX_VALUE) + 1L;
private static final int MAX_UINT16 = Math.abs(2 * Short.MAX_VALUE) + 1;
private static final short MAX_UINT8 = (short) (Math.abs(2 * Byte.MAX_VALUE) + 1);
/**
* Returns the unsigned equivalent of specified long, promoted to a BigInteger
*
* @param l the long to return as an unsigned value
* @return the unsigned value of l
*/
public static BigInteger unsigned(final long l) {
final BigInteger bi = BigInteger.ONE
.add(BigInteger.valueOf(Long.MAX_VALUE))
.add(BigInteger.valueOf(Long.MAX_VALUE));
return l > 0 ? BigInteger.valueOf(l) : bi.add(BigInteger.valueOf(l)).add(BigInteger.ONE);
}
/**
* Returns the unsigned equivalent of specified int, promoted to a long
*
* @param i the int to return as an unsigned value
* @return the unsigned value of i
*/
public static long unsigned(final int i) {
return i > 0 ? (long) i : MAX_UINT32 + (long) i + 1L;
}
/**
* Returns the unsigned equivalent of specified short, promoted to an int
*
* @param s the short to return as an unsigned value
* @return the unsigned value of s
*/
public static int unsigned(final short s) {
return s > 0 ? s : MAX_UINT16 + (int) s + 1;
}
/**
* Returns the unsigned equivalent of specified byte, promoted to a short
*
* @param b the byte to return as an unsigned value
* @return the unsigned value of b
*/
public static short unsigned(final byte b) {
return b > 0 ? (short) b : (short) (MAX_UINT8 + b + 1);
}
private UnsignedMath() {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment