com.github.isaichkindanila.crypt.lib.util.ConversionUtils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of crypt-lib Show documentation
Show all versions of crypt-lib Show documentation
Simple Java library for stream ciphers based encryption
The newest version!
package com.github.isaichkindanila.crypt.lib.util;
/**
* Utility class to handle primitive-to-bytes conversions.
*/
@SuppressWarnings("WeakerAccess")
public class ConversionUtils {
private ConversionUtils() {
}
/**
* Converts 4 bytes to integer using low-endian format.
*
* @param bytes array of bytes
* @param pos first index of 4 bytes to convert to integer
* @return integer parsed from bytes using low-endian format
*/
public static int bytesToInt(byte[] bytes, int pos) {
return bytes[pos] & 0xff
| ((bytes[pos + 1] & 0xff) << 8)
| ((bytes[pos + 2] & 0xff) << 16)
| ((bytes[pos + 3] & 0xff) << 24);
}
/**
* Converts 8 bytes to long using low-endian format.
*
* @param bytes array of bytes
* @param pos first index of 8 bytes to convert to long
* @return long parsed from bytes using low-endian format
*/
public static long bytesToLong(byte[] bytes, int pos) {
return (long) bytes[pos] & 0xff
| ((long) (bytes[pos + 1] & 0xff) << 8)
| ((long) (bytes[pos + 2] & 0xff) << 16)
| ((long) (bytes[pos + 3] & 0xff) << 24)
| ((long) (bytes[pos + 4] & 0xff) << 32)
| ((long) (bytes[pos + 5] & 0xff) << 40)
| ((long) (bytes[pos + 6] & 0xff) << 48)
| ((long) (bytes[pos + 7] & 0xff) << 56);
}
/**
* Converts integer to 4 bytes using low-endian format.
*
* @param x integer to convert to bytes
* @return 4 bytes representing integer in low-endian format
*/
public static byte[] intToBytes(int x) {
return new byte[]{
(byte) x,
(byte) (x >> 8),
(byte) (x >> 16),
(byte) (x >> 24)
};
}
/**
* Converts long to 8 bytes using low-endian format.
*
* @param x long to convert to bytes
* @return 8 bytes representing long in low-endian format
*/
public static byte[] longToBytes(long x) {
return new byte[]{
(byte) x,
(byte) (x >> 8),
(byte) (x >> 16),
(byte) (x >> 24),
(byte) (x >> 32),
(byte) (x >> 40),
(byte) (x >> 48),
(byte) (x >> 56),
};
}
}