package com.safeluck.aykj.utils; public final class BytesUtils { public static String bytesToHexString(byte[] src,int len){ return bytesToHexString(src,0,len); } public static String bytesToHexString(byte[] src){ return bytesToHexString(src,0,src.length); } public static String bytesToHexString(byte[] src,int start,int len){ StringBuilder stringBuilder = new StringBuilder(""); if (src == null || src.length <= 0) { return null; } for (int i = start; i < len; i++) { int v = src[i] & 0xFF; String hv = Integer.toHexString(v); if (hv.length() < 2) { stringBuilder.append(0); } stringBuilder.append(hv); } return stringBuilder.toString().toUpperCase(); } public static byte[] hexStringToBytes(String hexString) { if (hexString == null || hexString.equals("")) { return null; } hexString = hexString.toUpperCase(); int length = hexString.length() / 2; char[] hexChars = hexString.toCharArray(); byte[] d = new byte[length]; for (int i = 0; i < length; i++) { int pos = i * 2; d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1])); } return d; } private static byte charToByte(char c) { return (byte) "0123456789ABCDEF".indexOf(c); } public static byte xor(byte[] bytes,int start,int end) { if (bytes.length < end) { throw new RuntimeException("计算xor的时候size不足"); } int s1 = bytes[start]; for (int i = start + 1; i < end; i++) { s1 = s1 ^ bytes[i]; } return (byte)s1; } public static byte xor(byte[] bytes) { return xor(bytes,0,bytes.length); } public static String toHexString(byte b) { String hex = Integer.toHexString(b&0xff).toUpperCase(); if(hex.length()==1) { return "0"+hex; } return hex; } public static int sum(byte[] bytes,int start,int end) { if (bytes.length < end) { throw new RuntimeException("计算sum的时候size不足"); } int s1 = 0; for (int i = start; i < end; i++) { // System.out.println(bytes[i]&0xFF); s1 += (bytes[i]&0xFF); // System.out.println("sum="+s1); } return s1; // int sum = 0; // for(byte b:bytes) // { // sum+=b; // } // return sum; } public static int sum(byte[] bytes) { return sum(bytes,0,bytes.length); } public static int getInt32(byte[] bytes,int start){ int result = 0; int a = (bytes[0+start] & 0xff) << 24; int b = (bytes[1+start] & 0xff) << 16; int c = (bytes[2+start] & 0xff) << 8; int d = (bytes[3+start] & 0xff); result = a | b | c | d; return result; } }