Java异或运算、16进制字符串与byte数组互转、byte[]与int互转

运算法则:

异或运算

public String XOR_operation(String strHex_X,String strHex_Y){		//16进制字符异或运算
		String anotherBinary=Integer.toBinaryString(Integer.valueOf(strHex_X,16));	//16进制字符转二进制字符
		String thisBinary=Integer.toBinaryString(Integer.valueOf(strHex_Y,16));
		String result = "";
		if(anotherBinary.length() != 8){						//判断是否为8位二进制,否则左补零
			for (int i = anotherBinary.length(); i <8; i++) {
				anotherBinary = "0"+anotherBinary;
			}
		}
		if(thisBinary.length() != 8){
			for (int i = thisBinary.length(); i <8; i++) {
				thisBinary = "0"+thisBinary;
			}
		}
		for(int i=0;i<anotherBinary.length();i++){					//异或运算  相同取0 不同取1
			if(thisBinary.charAt(i)==anotherBinary.charAt(i))
				result+="0";
			else{
				result+="1";
			}
		}
		return Integer.toHexString(Integer.parseInt(result, 2));
	}

字节数组异或运算:

public String getXorByte(byte[] bytes){
		String temp = "00";
		for(int i = 0;i<bytes.length;i++){
			temp = XOR_operation(temp,Integer.toHexString(bytes[i] & 0xFF));
		}
		return  temp;
	}

字节数组转16进制字符串

public static String bytesToHex(byte[] bytes) {
		StringBuffer sb = new StringBuffer();
		for(int i = 0; i < bytes.length; i++) {
			String hex = Integer.toHexString(bytes[i] & 0xFF);
			if(hex.length() < 2){
				sb.append(0);
			}
			sb.append(hex);
		}
		return sb.toString();
	}

16进制字符串转byte数组

16进制字符转byte:

public static byte hexToByte(String inHex){
		return (byte)Integer.parseInt(inHex,16);
	}

16进制字符串转byte数组

public static byte[] hexToByteArray(String inHex){
   int hexlen = inHex.length();
   byte[] result;
   if (hexlen % 2 == 1){
      //奇数
      hexlen++;
      result = new byte[(hexlen/2)];
      inHex="0"+inHex;
   }else {
      //偶数
      result = new byte[(hexlen/2)];
   }
   int j=0;
   for (int i = 0; i < hexlen; i+=2){
      result[j]=hexToByte(inHex.substring(i,i+2));
      j++;
   }
   return result;
}

byte[]与int互转

private static int byteArrayToInt(byte[] var0) {
        return var0[0] & 255 | (var0[1] & 255) << 8 | (var0[2] & 255) << 16 | (var0[3] & 255) << 24;
    }

    private static byte[] intToByteArray(int var0) {
        return new byte[]{(byte)(var0 & 255), (byte)(var0 >> 8 & 255), (byte)(var0 >> 16 & 255), (byte)(var0 >> 24 & 255)};
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值