浏览 2153 次
锁定老帖子 主题:转化为字节流
该帖已经被评为新手帖
|
|
---|---|
作者 | 正文 |
发表时间:2008-03-10
package eccl.socket.tools; public class ByteOperator{ public ByteOperator(){ } /** * 长整形转化为byte类型 */ public static void putLong(byte[] buf,int offset,long value) { buf[offset + 0] = (byte) ((value >> 56) & 0xff); buf[offset + 1] = (byte) ((value >> 48) & 0xff); buf[offset + 2] = (byte) ((value >> 40) & 0xff); buf[offset + 3] = (byte) ((value >> 32) & 0xff); buf[offset + 4] = (byte) ((value >> 24) & 0xff); buf[offset + 5] = (byte) ((value >> 16) & 0xff); buf[offset + 6] = (byte) ((value >> 8) & 0xff); buf[offset + 7] = (byte) ((value >> 0) & 0xff); } /** * byte 型转化为 Long 类型 */ public static long getLong(byte[] bytes, int index) { return ((((long) bytes[index + 0] & 0xff) << 56) | (((long) bytes[index + 1] & 0xff) << 48) | (((long) bytes[index + 2] & 0xff) << 40) | (((long) bytes[index + 3] & 0xff) << 32) | (((long) bytes[index + 4] & 0xff) << 24) | (((long) bytes[index + 5] & 0xff) << 16) | (((long) bytes[index + 6] & 0xff) << 8) | (((long) bytes[index + 7] & 0xff) << 0)); } /** * 整形转化为byte类型 */ public static void putInt(byte[] buf,int offset,int value) { buf[offset+0] = (byte)((value >> 24) & 0xff); buf[offset+1] = (byte)((value >> 16) & 0xff); buf[offset+2] = (byte)((value >> 8) & 0xff); buf[offset+3] = (byte)((value >> 0) & 0xff); } /** * byte类型转换为int型 */ public static int getInt(byte[] bytes, int index) { return (int) ((((bytes[index + 0] & 0xff) << 24) | ((bytes[index + 1] & 0xff) << 16) | ((bytes[index + 2] & 0xff) << 8) | ((bytes[index + 3] & 0xff) << 0))); } /** * 浮点型转化为byte类型 */ public static void putFloat(byte[] buf,int offset,float value){ try { putInt(buf,offset,Float.floatToIntBits(value)); } catch (Exception ex) { System.out.print("convert the float to Byte is error!\n"); } } /** * byte类型转换为浮点型 */ public static float getFloat(byte[] bytes,int index){ int num = ((bytes[index]<<24)&0xFF000000)|((bytes[index+1]<<16)&0xFF0000)|((bytes[index+2]<<8)&0xFF00)|(bytes[index+3]&0xFF); float f = Float.intBitsToFloat(num); return f; } /** * byte 类型转换为 short型 */ public static short getShort(byte[] bytes, int index) { return (short) (((bytes[index] << 8) | bytes[index + 1] & 0xff)); } /** * 短整形转化为byte类型 */ public static void putShort(byte[] buf,int offset,short value) { buf[offset+0] = (byte)((value >> 8) & 0xff); buf[offset+1] = (byte)((value >> 0) & 0xff); } /** * 字符串转化为byte类型 */ public static void putStr(byte[] buf,int offset,int length,String value) { try{ byte[] tmpByte = value.getBytes(); for(int i=length-1;i>=0;i--){ // buf[offset+i] = tmpByte[i]; buf[offset+i] = tmpByte[i]; } }catch(Exception e) { System.out.print("convert the String to Byte is error!\n"+e); } } /** * byte型转换为字符串型 */ public static String getStr(byte[] bytes,int index){ byte[] str = new byte[4]; for(int i=0;i<4;i++){ str[i] = bytes[index+i]; } return new String(str); } } 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |