常用工具(十一)--BinaryUtils

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;
	}

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值