今天跟大家一起分享Java源码中关于字节数组(byte[ ])与int、long等类型数据之间的转换的算法,希望对你有用!
1. DataOutputStream类定义,该类位于package java.io;
public class DataOutputStream extends FilterOutputStream implements DataOutput
2. 在一个项目中。牵扯到需要将int或者long类型数据转换为字节数组。
JDK提供的API,源码:
/** * Writes a 32-bit int to the target stream. The resulting output is the * four bytes, highest order first, of {@code val}. * * @param val * the int to write to the target stream. * @throws IOException * if an error occurs while writing to the target stream. * @see DataInputStream#readInt() */ public final void writeInt(int val) throws IOException { buff[0] = (byte) (val >> 24); buff[1] = (byte) (val >> 16); buff[2] = (byte) (val >> 8); buff[3] = (byte) val; out.write(buff, 0, 4); written += 4; }
这是DataOutputStream类的writeInt方法源码,其原理很简单。
/** * Writes a 64-bit long to the target stream. The resulting output is the * eight bytes, highest order first, of {@code val}. * * @param val * the long to write to the target stream. * @throws IOException * if an error occurs while writing to the target stream. * @see DataInputStream#readLong() */ public final void writeLong(long val) throws IOException { buff[0] = (byte) (val >> 56); buff[1] = (byte) (val >> 48); buff[2] = (byte) (val >> 40); buff[3] = (byte) (val >> 32); buff[4] = (byte) (val >> 24); buff[5] = (byte) (val >> 16); buff[6] = (byte) (val >> 8); buff[7] = (byte) val; out.write(buff, 0, 8); written += 8; }
这是DataOutputStream类的writeLong方法源码,其原理跟writeInt类似!还有writeShort等,研究一下,你就可以写出属于自己的代码。
3. 将long类型转换为byte[ ]的常用算法:
/** * @param val * long数据类型 * @return 字节数组,长度为8 * @throws IOException */ public static byte[] getBytes(Long val) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); dos.writeLong(val); return baos.toByteArray(); }
/** * @param val * long数据类型 * @return 字节数组,长度为8 */ public static byte[] getBytes(Long val) { ByteBuffer buf = ByteBuffer.allocate(8); buf.order(ByteOrder.BIG_ENDIAN); buf.putLong(val); return buf.array(); }
4. 将lbyte[ ]类型转换为long的常用算法:
/** * byte数组转成long * * @param buffer字节数组 * @return long类型数据 */ public static long byteToLong(byte[] buffer) { long l = 0; // 最低位 long l0 = buffer[7] & 0xff; long l1 = buffer[6] & 0xff; long l2 = buffer[5] & 0xff; long l3 = buffer[4] & 0xff; long l4 = buffer[3] & 0xff; long l5 = buffer[2] & 0xff; long l6 = buffer[1] & 0xff; // 最高位 long l7 = buffer[0] & 0xff; // l0不变 l1 <<= 8; l2 <<= 16; l3 <<= 24; l4 <<= 8 * 4; l5 <<= 8 * 5; l6 <<= 8 * 6; l7 <<= 8 * 7; l = l0 | l1 | l2 | l3 | l4 | l5 | l6 | l7; return l; }
ok,到此为止,其他的类似算法大家各自发挥吧!!