import java.math.BigInteger;
public class BinaryUtils {
public static final int HEX_STRING_LENGTH = 16;
public static final int BIT64_LENGTH = 64;
public static String convertToBinary(int num, int length) {
String str = "";
for (int a = 0; a < length; a++) {
if (num % 2 == 1) {
str = "1" + str;
}
if (num % 2 == 0) {
str = "0" + str;
}
num = num / 2;
}
//System.out.println("The binary conversion is : " + str);
return str;
}
public static String toHex(String binaryString) {
BigInteger bigInteger = new BigInteger(binaryString.toString(), 2);
String resultString = bigInteger.toString(HEX_STRING_LENGTH).toUpperCase();
return appendZeroFromHeader(resultString);
}
// "0000111111111111111111111111111111111111111111110000111100001111"
// should be "0FFFFFFFFFFF0F0F"
private static String appendZeroFromHeader(String hexString){
int length = hexString.length();
if(length == HEX_STRING_LENGTH)
return hexString;
int lengthOfNeedingAppendedZero = HEX_STRING_LENGTH - length;
String zeros = String.format("%0"+Integer.toString(lengthOfNeedingAppendedZero)+"d", 0);
return zeros + hexString;
}
public static String appendZeroAfter(String hexString){
int length = hexString.length();
if(length == BIT64_LENGTH)
return hexString;
int lengthOfNeedingAppendedZero = BIT64_LENGTH - length;
StringBuilder builder = new StringBuilder();
for (int i = 0; i < lengthOfNeedingAppendedZero; i++) {
builder.append("0");
}
return hexString + builder.toString();
}
public static int toInt(String value){
if(value.contains("0x")){
value = value.substring(2, value.length());
return Integer.parseInt(value, 16);
}
return Integer.parseInt(value);
}
public static byte[] hexStrToByteArray(String str)
{
if (str == null) {
return null;
}
if (str.length() == 0) {
return new byte[0];
}
byte[] byteArray = new byte[str.length() / 2];
for (int i = 0; i < byteArray.length; i++){
String subStr = str.substring(2 * i, 2 * i + 2);
byteArray[i] = ((byte)Integer.parseInt(subStr, 16));
}
return byteArray;
}
public static Byte[] toBytes(byte[] bytesPrim) {
Byte[] bytes = new Byte[bytesPrim.length];
int i = 0;
for (byte b : bytesPrim) bytes[i++] = b; // Autoboxing
return bytes;
}
public static String hexToBinary(String hex) {
int i = Integer.parseInt(hex, 16);
String bin = Integer.toBinaryString(i);
return bin;
}
}
常用工具(十一)--BinaryUtils
最新推荐文章于 2022-03-01 15:26:07 发布