java 基本类型与byte[]相互转换

	//long类型转成byte数组
	public static byte[] longToBytes(long number) {
	        long temp = number;
	        byte[] b = new byte[8];
	        for (int i = 0; i < b.length; i++) {
	            b[i] = new Long(temp & 0xff).byteValue();// 将最低位保存在最低位
	        temp = temp >> 8; // 向右移8位
	    }
	    return b;
	}

	//byte数组转成long
	public static long bytesToLong(byte[] b) {
	
	    long s = 0;
	    long s0 = b[0] & 0xff;// 最低位
	    long s1 = b[1] & 0xff;
	    long s2 = b[2] & 0xff;
	    long s3 = b[3] & 0xff;
	    long s4 = b[4] & 0xff;// 最低位
	    long s5 = b[5] & 0xff;
	    long s6 = b[6] & 0xff;
	    long s7 = b[7] & 0xff;
	
	    // s0不变
	    s1 <<= 8;
	    s2 <<= 16;
	    s3 <<= 24;
	    s4 <<= 8 * 4;
	    s5 <<= 8 * 5;
	    s6 <<= 8 * 6;
	    s7 <<= 8 * 7;
	    s = s0 | s1 | s2 | s3 | s4 | s5 | s6 | s7;
	    return s;
	}

	public static byte[] intToBytes(int number) {
		
	    int temp = number;
	    byte[] b = new byte[4];
	
	    for (int i = 0; i < b.length; i++) {
	        b[i] = new Integer(temp & 0xff).byteValue();// 将最低位保存在最低位
	        temp = temp >> 8; // 向右移8位
	    }
	    return b;
	}

	public static int bytesToInt(byte[] b) {
	
	    int s = 0;
	    int s0 = b[0] & 0xff;// 最低位
	    int s1 = b[1] & 0xff;
	    int s2 = b[2] & 0xff;
	    int s3 = b[3] & 0xff;
	    s3 <<= 24;
	    s2 <<= 16;
	    s1 <<= 8;
	    s = s0 | s1 | s2 | s3;
	    return s;
	}
	
	//浮点到字节转换
	public static byte[] doubleToBytes(double d)
	{
		byte writeBuffer[]= new byte[8];
	     long v = Double.doubleToLongBits(d);
	        writeBuffer[0] = (byte)(v >>> 56);
	        writeBuffer[1] = (byte)(v >>> 48);
	        writeBuffer[2] = (byte)(v >>> 40);
	        writeBuffer[3] = (byte)(v >>> 32);
	        writeBuffer[4] = (byte)(v >>> 24);
	        writeBuffer[5] = (byte)(v >>> 16);
	        writeBuffer[6] = (byte)(v >>>  8);
	        writeBuffer[7] = (byte)(v >>>  0);
	        return writeBuffer;

	}
	
	//字节到浮点转换
	public static double bytesToDouble(byte[] readBuffer)
	{
	     return Double.longBitsToDouble((((long)readBuffer[0] << 56) +
	                ((long)(readBuffer[1] & 255) << 48) +
	                ((long)(readBuffer[2] & 255) << 40) +
	                ((long)(readBuffer[3] & 255) << 32) +
	                ((long)(readBuffer[4] & 255) << 24) +
	                ((readBuffer[5] & 255) << 16) +
	                ((readBuffer[6] & 255) <<  8) +
	                ((readBuffer[7] & 255) <<  0))
	          );
	}

以上代码经过了我测试。请注意double和byte[]的相互转换,目前网上流传最多的那个算法经我测试不能正常工作(当数值小于10.0时),我这个是参考一个VC程序员的代码改成的。
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值