Created
November 30, 2015 10:16
-
-
Save bassemZohdy/60863787ee00128d1b31 to your computer and use it in GitHub Desktop.
This file contains 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
import java.util.function.Function; | |
public class BytesConvertUtils { | |
public static final Function<Integer, byte[]> intToBytes = l -> { | |
int count = Integer.BYTES; | |
return new byte[] { (byte) ((l >> 8 * --count) & 0xFF), | |
(byte) ((l >> 8 * --count) & 0xFF), | |
(byte) ((l >> 8 * --count) & 0xFF), | |
(byte) ((l >> 8 * --count) & 0xFF) }; | |
}; | |
public static final Function<Float, byte[]> floatToBytes = intToBytes | |
.compose(Float::floatToIntBits); | |
public static final Function<byte[], Integer> bytesToInt = b -> { | |
int count = Integer.BYTES; | |
return ((b[8 - count] & 0xFF) << 8 * --count) | |
| ((b[8 - count] & 0xFF) << 8 * --count) | |
| ((b[8 - count] & 0xFF) << 8 * --count) | |
| ((b[8 - count] & 0xFF) << 8 * --count); | |
}; | |
public static final Function<byte[], Float> bytesToFloat = bytesToInt | |
.andThen(Float::intBitsToFloat); | |
public static final Function<Long, byte[]> longToBytes = l -> { | |
int count = Long.BYTES; | |
return new byte[] { (byte) ((l >> 8 * --count) & 0xFF), | |
(byte) ((l >> 8 * --count) & 0xFF), | |
(byte) ((l >> 8 * --count) & 0xFF), | |
(byte) ((l >> 8 * --count) & 0xFF), | |
(byte) ((l >> 8 * --count) & 0xFF), | |
(byte) ((l >> 8 * --count) & 0xFF), | |
(byte) ((l >> 8 * --count) & 0xFF), | |
(byte) ((l >> 8 * --count) & 0xFF) }; | |
}; | |
public static final Function<Double, byte[]> doubleToBytes = longToBytes | |
.compose(Double::doubleToLongBits); | |
public static final Function<byte[], Long> bytesToLong = b -> { | |
int count = Long.BYTES; | |
return ((b[8 - count] & 0xFFL) << 8 * --count) | |
| ((b[8 - count] & 0xFFL) << 8 * --count) | |
| ((b[8 - count] & 0xFFL) << 8 * --count) | |
| ((b[8 - count] & 0xFFL) << 8 * --count) | |
| ((b[8 - count] & 0xFFL) << 8 * --count) | |
| ((b[8 - count] & 0xFFL) << 8 * --count) | |
| ((b[8 - count] & 0xFFL) << 8 * --count) | |
| ((b[8 - count] & 0xFFL) << 8 * --count); | |
}; | |
public static final Function<byte[], Double> bytesToDouble = bytesToLong | |
.andThen(Double::longBitsToDouble); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment