| | |
| | | import java.io.UnsupportedEncodingException; |
| | | import java.nio.ByteBuffer; |
| | | import java.nio.ByteOrder; |
| | | import java.nio.charset.StandardCharsets; |
| | | import java.util.zip.CRC32; |
| | | |
| | | import static oracle.security.pki.util.SignatureAlgorithms.i; |
| | | |
| | | /** |
| | | * @Description: 字节工具类 |
| | |
| | | * byte数组转中文字符串 |
| | | */ |
| | | public static String bytesToStringZh(byte[] bytes) { |
| | | //ByteBuffer buffer = ByteBuffer.wrap(bytes); // byteArray 是包含字节数组的变量 |
| | | //try { |
| | | // return new String(buffer.array(), "GBK"); |
| | | //} catch (UnsupportedEncodingException e) { |
| | | // e.printStackTrace(); |
| | | //} |
| | | //return ""; |
| | | String zhStr = ""; |
| | | try { |
| | | int position = ByteUtils.findIndexOfDoubleZero(bytes); |
| | |
| | | * byte数组转整型 |
| | | */ |
| | | public static int bytesToDecimal(byte[] byteArray) { |
| | | //ByteBuffer buffer = ByteBuffer.wrap(byteArray); // byteArray 是包含字节数组的变量 |
| | | //return buffer.getInt(); |
| | | int decimalValue = 0; |
| | | for (int i = 0; i < byteArray.length; i++) { |
| | | decimalValue = (decimalValue << 8) | (byteArray[i] & 0xFF); |
| | |
| | | return decimalValue; |
| | | } |
| | | |
| | | |
| | | /** |
| | | * byte数组转Double |
| | | */ |
| | | public static double bytesToDouble(byte[] byteArray) { |
| | | // 创建一个ByteBuffer并设置字节顺序为大端 |
| | | // 创建一个ByteBuffer |
| | | ByteBuffer buffer = ByteBuffer.wrap(byteArray); |
| | | //设置字节顺序为大端 |
| | | buffer.order(ByteOrder.LITTLE_ENDIAN); |
| | | // 从ByteBuffer中获取double值 |
| | | double doubleValue = buffer.getDouble(); |
| | |
| | | return buffer.array(); |
| | | } |
| | | |
| | | |
| | | /** |
| | | * double转byte数组 |
| | | */ |
| | | public static byte[] doubleToBytes(double d) { |
| | | long value = Double.doubleToRawLongBits(d); |
| | | byte[] byteRet = new byte[8]; |
| | | for (int i = 0; i < 8; i++) { |
| | | byteRet[i] = (byte) ((value >> 8 * i) & 0xff); |
| | | } |
| | | return byteRet; |
| | | // 创建一个 ByteBuffer,分配足够的空间来存储一个 float 值 |
| | | ByteBuffer buffer = ByteBuffer.allocate(Double.BYTES); |
| | | // 将 float 值写入 ByteBuffer |
| | | buffer.putDouble(d); |
| | | // 获取字节数组 |
| | | return buffer.array(); |
| | | } |
| | | |
| | | /** |
| | | * float转byte数组 |
| | | */ |
| | |
| | | // 获取字节数组 |
| | | return buffer.array(); |
| | | } |
| | | |
| | | /** |
| | | * byte数组拼接 |
| | | */ |
| | |
| | | // System.out.print("校验:"+DatatypeConverter.printHexBinary(bytes));//打印crc32的校验值 |
| | | return bytes; |
| | | } |
| | | |
| | | /** |
| | | * byte转二进制字符串 |
| | | */ |
| | | public static String byteToBitString(byte b) { |
| | | return String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0'); |
| | | } |
| | | /** |
| | | * 去除包头包尾 |
| | | * 刘苏义 |