Skip to content

Instantly share code, notes, and snippets.

@chrisfesler
Created January 19, 2012 05:16
Show Gist options
  • Save chrisfesler/1638122 to your computer and use it in GitHub Desktop.
Save chrisfesler/1638122 to your computer and use it in GitHub Desktop.
Vanilla unsigned ints
package org.fesler.vanilla;
import java.io.*;
public enum Unsigned {;
public static int add(int i, int j) {
return i + j;
}
public static int subtract(int i, int j) {
return i - j;
}
public static int multiply(int i, int j) {
return i * j;
}
public static int shiftLeft(int i, int n) {
return i << n;
}
public static int shiftRight(int i, int n) {
return i >>> n;
}
public static int parseUnsignedInt(String text) {
long tmp = Long.parseLong(text);
return (((int) (tmp >> 1)) << 1) + ((int) (tmp & 1));
}
public static String toString(int n) {
return Long.toString((((long) (n >>> 1)) << 1) + (n & 1));
}
// missing methods
public static void writeUnsignedInt(DataOutputStream dos, int uint) throws IOException {
dos.writeInt(uint);
}
public static int readUnsignedInt(DataInputStream dis) throws IOException {
return dis.readInt();
}
public static void main(String... args) throws Exception {
assert "2500000000".equals(toString(subtract(add(2000 * 1000 * 1000, 1750 * 1000 * 1000), 1250 * 1000 * 1000)));
assert "2500000001".equals(toString(add(subtract(add(2000 * 1000 * 1000, 1750 * 1000 * 1000), 1250 * 1000 * 1000), 1)));
assert "4000000000".equals(toString(multiply(1000 * 1000, 4000)));
assert "3200000000".equals(toString(shiftLeft(100 * 1000 * 1000, 5)));
assert "1000000000".equals(toString(shiftRight(parseUnsignedInt("4000000000"), 2)));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
writeUnsignedInt(dos, multiply(1000 * 1000, 4000));
writeUnsignedInt(dos, parseUnsignedInt("3210000000"));
dos.close();
DataInputStream dis = new DataInputStream(new ByteArrayInputStream(baos.toByteArray()));
assert "4000000000".equals(toString(readUnsignedInt(dis)));
assert "3210000000".equals(toString(readUnsignedInt(dis)));
dis.close();
}
}
@chrisfesler
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment