importjava.nio.ByteBuffer;publicclassByteToLongConverter{publicstaticvoidmain(String[]args){// 创建一个字节数组,长度为8(long类型占用8个字节)byte[]byteArray=newbyte[]{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01};// 使用ByteBuffer
这段代码定义了一个byteArrayToLong方法,该方法接受一个byte数组作为输入,并返回一个long值。在main方法中,我们提供了一个示例字节数组,并调用byteArrayToLong方法将其转换为long值,然后输出结果。
publicclassByteToLongConverter{publicstaticvoidmain(String[]args){// Step 1: 创建一个byte数组byte[]byteArray=newbyte[5];byteArray[0]=0x01;byteArray[1]=0x02;byteArray[2]=0x03;byteArray[3]=0x04;byteArray[4]=0x05;// Step 2: 初始化long变量longresult=0L;// Step 3: 遍历byte数组并逐...
public static byte[] long2byte(long res) { byte[] buffer = new byte[8]; for (int i = 0; i < 8; i++) { int offset = 64 - (i + 1) * 8; buffer[i] = (byte) ((res >> offset) & 0xff); } return buffer; } public static long byteArrayToLong(byte[] b){ long value...
java.io.DataInputStream 同样提供了readLong,readLong,readLong….方法,只要将byte[]转换为DataInputStream就可以实现所有primitive类型的数据读取,参见javadoc。 完整测试代码 下面的Junit 测试代码计算String 的MD5校验码(16 bytes),然后使用上述方式分别将16 bytes转换为2个long(大端模式)然后以16进制模式输出结果,以验...
public static long byteArrayToLong8(byte[] b) { return (long)b[9] & 0xFF | (long)(b[8] & 0xFF) << 8| (long)(b[7] & 0xFF) << 16 | (long)(b[6] & 0xFF) << 24 | (long)(b[5] & 0xFF) << 32| (long)(b[4] & 0xFF) << 40| ...
result[2] = (byte) ((i >> 8) & 0xFF); result[3] = (byte) (i & 0xFF); return result; } /** * 转换long型为byte数组 * * @param bb * @param x * @param index */ public byte[] longToByteArray(long x, int index) { ...
public static long[] byteArrayToIntArray(byte[] b, int offset) { long[] arr= new long[b.length]; for (int i = 0; i < 4; i++) { int shift= (4 - 1 - i) * 8; arr[i] = (b[i + offset] & 0x000000FF) << shift; } return arr; }挨...
return buffer.array(); } public static long bytesToLong(byte[] bytes) { buffer.put(bytes, 0, bytes.length); buffer.flip();//need flip return buffer.getLong(); } 测试代码: //测试 long 转 byte 数组 long long1 = 2223; byte[] bytesLong = longToBytes(long1); ...
importjava.nio.ByteBuffer;publicclassByteToLongExample{publicstaticvoidmain(String[]args){// 步骤1: 创建一个字节数组byte[]byteArray={0x12,0x34,0x56,0x78};// 步骤2: 使用 ByteBuffer 类将字节数组包装成 ByteBuffer 对象ByteBufferbuffer=ByteBuffer.wrap(byteArray);// 步骤3: 调用 ByteBuffer 对象的 ...