libKonogonka/src/main/java/libKonogonka/Converter.java

72 lines
2.5 KiB
Java
Raw Normal View History

2022-08-10 15:55:50 +03:00
/*
2022-08-10 20:20:10 +03:00
Copyright 2019-2022 Dmitry Isaenko
2022-08-10 15:55:50 +03:00
2022-08-10 20:20:10 +03:00
This file is part of libKonogonka.
2022-08-10 15:55:50 +03:00
2022-08-10 20:20:10 +03:00
libKonogonka is free software: you can redistribute it and/or modify
2022-08-10 15:55:50 +03:00
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2022-08-10 20:20:10 +03:00
libKonogonka is distributed in the hope that it will be useful,
2022-08-10 15:55:50 +03:00
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
2022-08-10 20:20:10 +03:00
along with libKonogonka. If not, see <https://www.gnu.org/licenses/>.
2022-08-10 15:55:50 +03:00
*/
package libKonogonka;
2022-12-07 04:22:23 +03:00
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
2022-08-10 15:55:50 +03:00
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
2022-09-05 00:39:48 +03:00
public class Converter {
2022-12-07 04:22:23 +03:00
private final static Logger log = LogManager.getLogger(Converter.class);
2022-08-10 15:55:50 +03:00
public static int getLEint(byte[] bytes, int fromOffset){
2022-12-07 04:22:23 +03:00
if (fromOffset < 0 || fromOffset >= bytes.length)
log.debug("\tLen =" + bytes.length + "\tFrom =" + fromOffset);
2022-08-10 15:55:50 +03:00
return ByteBuffer.wrap(bytes, fromOffset, 0x4).order(ByteOrder.LITTLE_ENDIAN).getInt();
}
public static long getLElong(byte[] bytes, int fromOffset){
return ByteBuffer.wrap(bytes, fromOffset, 0x8).order(ByteOrder.LITTLE_ENDIAN).getLong();
}
/**
2022-09-05 00:39:48 +03:00
* Convert (usually unsigned) int to long. Workaround to store unsigned int
2022-08-10 15:55:50 +03:00
* @param bytes original array
* @param fromOffset start position of the 4-bytes value
* */
public static long getLElongOfInt(byte[] bytes, int fromOffset){
final byte[] holder = new byte[8];
System.arraycopy(bytes, fromOffset, holder, 0, 4);
return ByteBuffer.wrap(holder).order(ByteOrder.LITTLE_ENDIAN).getLong();
}
public static String byteArrToHexString(byte[] bArr){
if (bArr == null)
return "";
StringBuilder sb = new StringBuilder();
for (byte b: bArr)
sb.append(String.format("%02x", b));
return sb.toString();
}
public static String longToOctString(long value){
return String.format("%64s", Long.toBinaryString( value )).replace(' ', '0');
}
public static byte[] flip(byte[] bytes){
int size = bytes.length;
byte[] ret = new byte[size];
for (int i = 0; i < size; i++){
ret[size-i-1] = bytes[i];
}
return ret;
}
}