java高效基本类型与字节数组互相转换

java基本类型与字节数组互相转换

前情提要

在一些读文件流,或者网络数据传输时,我们直接接触的一定是一串java字节码,
如何高效把基本类型转换成我们的字节数组就是必须要要求的

实现流程思路

在这里插入图片描述
在这里插入图片描述

int 转 字节数组

public static byte[] int2Bytes(int n) {
     //自己数组的长度就是我们的int在内存中占用的大小==
   	int len = Integer.SIZE/8;##ddd##
   	byte[] bytes = new byte[len];
   	for(int i=0; i<len; i++ ) {
         //这里特别重要,主要目的是将我们的int数字的高位一次移动到字节数组中==
         //大家都知道int总共占用4个字节,转化到这里,就是将int的二进制码分段存储==
         //这里有个技巧 n*8 = n<<3
   		bytes[i] = (byte) (n >> ((len-1-i)<<3));
   	}
   	return bytes;
   }

short 转字节数组

public static byte[] short2Bytes(short n) {
		int len = Short.SIZE/8;
		byte[] bytes = new byte[len];
		for(int i=0; i<len; i++ ) {
			bytes[i] = (byte) (n >>> ((len-1-i)<<3));
		}
		return bytes;
	}

char 转字节数组

  public static byte[] char2Bytes(char n) {
		int len = Character.SIZE/8;
		byte[] bytes = new byte[len];
		for(int i=0; i<len; i++ ) {
			bytes[i] = (byte) (n >>> ((len-1-i)<<3));
		}
		return bytes;
	}

long 转字节数组

  	public static byte[]  long2Bytes(long n) {
		int len = Long.SIZE/8;
		byte[] bytes = new byte[len];
		for(int i=0; i<len; i++ ) {
			bytes[i] = (byte) (n >>> ((len-1-i)<<3));
		}
		return bytes;
	}

字节数组转int

	public static int bytes2Int(byte[] bytes) {
		int result=0;
		int len = bytes.length;
		//result = ((bytes[3] & 0xff)) | ((bytes[2] & 0xff) << 8)| ((bytes[1] & 0xff) << 16) | ((bytes[0])<<24);
		for(int i= len-1;i>=0; i--){
			result |= (i==0 ? bytes[i]:(bytes[i] & 0xff)) << ((len-1-i)<<3);
		}
		return result;
	}

字节数组转short

	public static short bytes2Short(byte[] bytes) {
		short result=0;
		int len = bytes.length;
		for(int i=len-1;i>=0; i--){
			result |= (short)(i==0 ? bytes[i]:(bytes[i] & 0xff)) << ((len-1-i)<<3);
		}
		return result;
	}

字节数组转char

	public static char bytes2Char(byte[] bytes) {
		char result=0;
		int len = bytes.length;
		for(int i=bytes.length-1;i>=0; i--){
			result |= (i==0 ? bytes[i]:(bytes[i] & 0xff)) << ((len-1-i)<<3);
		}
		return result;
	}

字节数组转long

	public static long bytes2Long(byte[] bytes) {
		long result=0;
		int len = bytes.length;
		for(int i=len-1;i>=0; i--){
			result |= (long)(i==0 ? bytes[i]:(bytes[i] & 0xff)) << ((len-1-i)<<3);
		}
		return result;
	}
	

时间不多啦

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值