首页

通过定义字节工具类BytesUtils将基本数据类型转换为字节数组byte[]代码示例说明

标签:字节工具类,BytesUtils,将基本数据类型转换为字节数组byte[]     发布时间:2018-10-02   

一、前言

通过定义BytesUtils字节工具类,将基本数据类型short/int/float/long/double等转换为byte[]字节数组,详情参见代码示例说明部分。

二、代码示例

public class BytesUtils {@b@@b@	public static final int BYTE_LEN = 1;@b@	public static final int SHORT_LEN = 2;@b@	public static final int INT_LEN = 4;@b@	public static final int FLOAT_LEN = 4;@b@	public static final int LONG_LEN = 8;@b@	public static final int DOUBLE_LEN = 8;@b@  @b@	@b@	public static byte[] shortToBytes(short num) {@b@		byte[] bytes=new byte[SHORT_LEN];@b@		int startIndex=0;@b@		bytes[startIndex] = (byte) (num & 0xff);@b@		bytes[startIndex + 1] = (byte) ((num >> 8) & 0xff);@b@		return bytes;@b@	}@b@		@b@	public static byte[] intToBytes(int num ) {@b@		byte[] bytes=new byte[INT_LEN];@b@		int startIndex=0;@b@		bytes[startIndex + 0] = (byte) (num & 0xff);@b@		bytes[startIndex + 1] = (byte) ((num >> 8) & 0xff);@b@		bytes[startIndex + 2] = (byte) ((num >> 16) & 0xff);@b@		bytes[startIndex + 3] = (byte) ((num >> 24) & 0xff);@b@		return bytes;@b@	}@b@	@b@@b@	public static byte[] floatToBytes(float fnum) {@b@		return intToBytes(Float.floatToIntBits(fnum));@b@	}@b@@b@	@b@	public static byte[] longToBytes(long lnum) {@b@		byte[] bytes=new byte[LONG_LEN];@b@		int startIndex=0;@b@		for (int i = 0; i < 8; i++)@b@			bytes[startIndex + i] = (byte) ((lnum >> (i * 8)) & 0xff);@b@		return bytes;@b@	}@b@	@b@@b@	public static byte[] doubleToBytes(double dnum) {@b@		return longToBytes(Double.doubleToLongBits(dnum));@b@	}@b@@b@}