Skip to content

Instantly share code, notes, and snippets.

@InvisibleTech
Created January 5, 2016 02:36
Show Gist options
  • Save InvisibleTech/da6345f7b4b6083aaa0c to your computer and use it in GitHub Desktop.
Save InvisibleTech/da6345f7b4b6083aaa0c to your computer and use it in GitHub Desktop.
A way to get the sign of values using one method in Java and not using inequality operators, strings of the values and so forth.
package org.invisibletech;
import static org.junit.Assert.*;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class CanDetermineSignTest {
@Rule public ExpectedException expectedException = ExpectedException.none();
@Test
public void shouldRaiseException_Given_NaNDouble() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("NaN");
IndicateSign.signOf(Double.NaN);
}
@Test
public void shouldReturnSign_Given_ZerosDouble() {
assertEquals(-1, IndicateSign.signOf(-0.0));
assertEquals(1, IndicateSign.signOf(0.0));
}
@Test
public void shouldReturnSign_Given_DoubleInfinities() {
assertEquals(1, IndicateSign.signOf(Double.POSITIVE_INFINITY));
assertEquals(-1, IndicateSign.signOf(Double.NEGATIVE_INFINITY));
}
@Test
public void shouldReturnSign_Given_Longs() {
assertEquals(1, IndicateSign.signOf(Long.MAX_VALUE));
assertEquals(-1, IndicateSign.signOf(Long.MIN_VALUE));
}
}
package org.invisibletech;
import java.nio.ByteBuffer;
import java.util.Optional;
public class IndicateSign {
public static int signOf(double d) {
Double validated = Optional.of(d).filter(x -> !Double.isNaN(x)).orElseThrow(() -> new IllegalArgumentException("NaN has no sign."));
byte[] array = ByteBuffer.allocate(Double.BYTES).putDouble(validated).array();
return testSignage(array);
}
public static int signOf(long l) {
byte[] array = ByteBuffer.allocate(Long.BYTES).putLong(l).array();
return testSignage(array);
}
private static int testSignage(byte[] array) {
return (array[0] & 0x80) != 0 ? -1 : 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment