Created
January 5, 2016 02:36
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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