Add method to get character precision
This method allows to find out, how
many characters represent a hash, if
base32 encoding is possible.
diff --git a/src/main/java/ch/hsr/geohash/GeoHash.java b/src/main/java/ch/hsr/geohash/GeoHash.java
index c9fe284..0645b24 100644
--- a/src/main/java/ch/hsr/geohash/GeoHash.java
+++ b/src/main/java/ch/hsr/geohash/GeoHash.java
@@ -12,7 +12,7 @@
import java.util.HashMap;
import java.util.Map;
-@SuppressWarnings({ "JavaDoc" })
+@SuppressWarnings("javadoc")
public final class GeoHash implements Comparable<GeoHash>, Serializable {
private static final long serialVersionUID = -8553214249630252175L;
private static final int[] BITS = { 16, 8, 4, 2, 1 };
@@ -185,6 +185,18 @@
return bits >> insignificantBits;
}
+ /**
+ * Returns the number of characters that represent this hash.
+ * @throws IllegalStateException when the hash cannot be encoded in base32, i.e. when the precision is not a multiple of 5.
+ */
+ public int getCharacterPrecision() {
+ if (significantBits % 5 != 0) {
+ throw new IllegalStateException(
+ "precision of GeoHash is not divisble by 5: " + this);
+ }
+ return significantBits / 5;
+ }
+
public static GeoHash fromOrd(long ord, int significantBits) {
int insignificantBits = 64 - significantBits;
return fromLongValue(ord << insignificantBits, significantBits);
diff --git a/src/test/java/ch/hsr/geohash/GeoHashTest.java b/src/test/java/ch/hsr/geohash/GeoHashTest.java
index fd8df09..9a11c70 100644
--- a/src/test/java/ch/hsr/geohash/GeoHashTest.java
+++ b/src/test/java/ch/hsr/geohash/GeoHashTest.java
@@ -430,6 +430,19 @@
assertTrue(prev2.compareTo(prev1) < 0);
assertTrue(prev2.compareTo(hash) == 0);
}
+
+ @Test(expected = IllegalStateException.class)
+ public void testGetCharacterPrecisionThrows() throws Exception {
+ GeoHash hash = GeoHash.withBitPrecision(37.7, -122.52, 32);
+ hash.getCharacterPrecision();
+ }
+
+ @Test
+ public void testGetCharacterPrecisionWorksWhenPrecisionIsMultipleOfFive() throws Exception {
+ GeoHash hash = GeoHash.withBitPrecision(37.7, -122.52, 60);
+ int precision = hash.getCharacterPrecision();
+ assertEquals(precision, 12);
+ }
@Test
public void testStepsBetween() {