From 6ba06d7ea1a3cdd4cd9f20317b48d2faf7c52c51 Mon Sep 17 00:00:00 2001 From: ZhouXY108 Date: Wed, 27 Nov 2024 21:25:19 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=20ByteArrayTools?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../plusone/commons/util/ByteArrayTools.java | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/main/java/xyz/zhouxy/plusone/commons/util/ByteArrayTools.java diff --git a/src/main/java/xyz/zhouxy/plusone/commons/util/ByteArrayTools.java b/src/main/java/xyz/zhouxy/plusone/commons/util/ByteArrayTools.java new file mode 100644 index 0000000..70725e0 --- /dev/null +++ b/src/main/java/xyz/zhouxy/plusone/commons/util/ByteArrayTools.java @@ -0,0 +1,57 @@ +/* + * Copyright 2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xyz.zhouxy.plusone.commons.util; + +import com.google.common.annotations.Beta; + +/** + * ByteArrayTools + * + *

byte 数组工具类 + * + * @author ZhouXY + */ +@Beta +public class ByteArrayTools { + + public static byte[] longToByteArray(long value) { + final byte[] bytes = new byte[8]; + fillToByteArrayInternal(value, bytes, 0); + return bytes; + } + + public static void fillToByteArray(long value, final byte[] bytes) { + AssertTools.checkArgument(bytes != null && bytes.length >= 8); + fillToByteArrayInternal(value, bytes, 0); + } + + public static void fillToByteArray(long value, final byte[] bytes, int startIndex) { + AssertTools.checkArgument(bytes != null && bytes.length >= startIndex + 8); + fillToByteArrayInternal(value, bytes, startIndex); + } + + private static void fillToByteArrayInternal(long value, final byte[] bytes, int startIndex) { + for (int i = 0; i < 8; i++) { + int offset = 8 * (7 - i); + bytes[startIndex + i] = (byte) ((value & (0xFFL << offset)) >> offset); + } + } + + private ByteArrayTools() { + throw new IllegalStateException("Utility class"); + } +}