From 85b0ee4bae215560010d0e6d0641705923a1aaa3 Mon Sep 17 00:00:00 2001 From: ‘liusuyi’ <1951119284@qq.com> Date: 星期五, 03 十一月 2023 10:42:53 +0800 Subject: [PATCH] 优化工具类 --- src/main/java/com/ard/utils/other/ByteUtils.java | 42 ++++++++++++++++++++---------------------- 1 files changed, 20 insertions(+), 22 deletions(-) diff --git a/src/main/java/com/ard/utils/other/ByteUtils.java b/src/main/java/com/ard/utils/other/ByteUtils.java index f89e0e9..bda4b8c 100644 --- a/src/main/java/com/ard/utils/other/ByteUtils.java +++ b/src/main/java/com/ard/utils/other/ByteUtils.java @@ -5,7 +5,10 @@ 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: 瀛楄妭宸ュ叿绫� @@ -27,20 +30,13 @@ * byte鏁扮粍杞腑鏂囧瓧绗︿覆 */ public static String bytesToStringZh(byte[] bytes) { - String zhStr = ""; + ByteBuffer buffer = ByteBuffer.wrap(bytes); // byteArray 鏄寘鍚瓧鑺傛暟缁勭殑鍙橀噺 try { - int position = ByteUtils.findIndexOfDoubleZero(bytes); - if (position != -1) { - byte[] result = new byte[position]; - System.arraycopy(bytes, 0, result, 0, position); - zhStr = new String(result, "GBK"); - } else { - zhStr = new String(bytes, "GBK"); - } + return new String(buffer.array(), "GBK"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } - return zhStr; + return ""; } /** @@ -71,19 +67,18 @@ * byte鏁扮粍杞暣鍨� */ public static int bytesToDecimal(byte[] byteArray) { - int decimalValue = 0; - for (int i = 0; i < byteArray.length; i++) { - decimalValue = (decimalValue << 8) | (byteArray[i] & 0xFF); - } - return decimalValue; + ByteBuffer buffer = ByteBuffer.wrap(byteArray); // byteArray 鏄寘鍚瓧鑺傛暟缁勭殑鍙橀噺 + return buffer.getInt(); } + /** * byte鏁扮粍杞珼ouble */ public static double bytesToDouble(byte[] byteArray) { - // 鍒涘缓涓�涓狟yteBuffer骞惰缃瓧鑺傞『搴忎负澶х + // 鍒涘缓涓�涓狟yteBuffer ByteBuffer buffer = ByteBuffer.wrap(byteArray); + //璁剧疆瀛楄妭椤哄簭涓哄ぇ绔� buffer.order(ByteOrder.LITTLE_ENDIAN); // 浠嶣yteBuffer涓幏鍙杁ouble鍊� double doubleValue = buffer.getDouble(); @@ -124,17 +119,19 @@ return buffer.array(); } + /** * double杞琤yte鏁扮粍 */ 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杞琤yte鏁扮粍 */ @@ -146,6 +143,7 @@ // 鑾峰彇瀛楄妭鏁扮粍 return buffer.array(); } + /** * byte鏁扮粍鎷兼帴 */ -- Gitblit v1.9.3