java 整形数组、字节流的互转

前言

某些时候,我们想存储一些整形、长整形的内容到一些地方。当然你可能会用“,”分隔来存,比如:

123,35,23533,234

这种形式并没有错,但存以几个缺点:

  • 字符串格式,占用空间太多,在java里,以上字符串至少条占16*2=32Byte
  • 不管是读取,还是写入,都 要把字符串转化为整形或相反,大家都应该知道字符串的操作对性能的影响还是挺大的

那么我们把它直接用整形的字节流来存储,会怎么样呢?

  • 不需要互转,节省开销
  • 空间:4*4=16byte,效果也是很明显的

问题来源

我这里说下的我一个应用实例。也就是我开发这个网站(ZHUTIBO)的时候,右上解不是有个搜索。这是个全文检索,涉及过的朋友应该知道全文检索有一个不太乐观的地方:

更新索引比较迟缓,因为影响性能。所以我们发表的文章不能及时被搜索到。然后我们就跟据需求重新写了一个全文检索功能。中间有一个问题就是快速存取一堆文档号,这就是问题的由来

正题

以下算法是本人改写自Java官网的RandomAccessFile类,性能上有一定的保障,大家可以放心使用。

package com.zhutibo.it.service;

import java.io.EOFException;
import java.io.IOException;

public class TypeService {
	
	public int[] convertByteArrToIntArr(byte[] byteArr) {
		
		int remained = 0;
		int intNum = 0;
		
		remained = byteArr.length % 4;
		if(remained != 0){
			throw new RuntimeException();
		}
		
		//把字节数组转化为int[]后保留的个数.
		intNum = byteArr.length / 4;
		
		//
		int[] intArr = new int[intNum];
		
		int ch1, ch2, ch3, ch4;
		for(int j=0, k=0; j<intArr.length; j++, k+=4){
			
			ch1 = byteArr[k];
			ch2 = byteArr[k+1];
			ch3 = byteArr[k+2];
			ch4 = byteArr[k+3];
			
			//以下内容用于把字节的8位, 不按照正负, 直接放到int的后8位中.
			if (ch1 < 0){
				ch1 = 256 + ch1;
			}
			if (ch2 < 0){
				ch2 = 256 + ch2;
			}
			if (ch3 < 0){
				ch3 = 256 + ch3;
			}
			if (ch4 < 0){
				ch4 = 256 + ch4;
			}
			
			intArr[j] = (ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0);
		}
		
		return intArr;
	}
	
	public byte[] convertIntArrToByteArr(int[] intArr){
		
		int byteNum = intArr.length * 4;
		byte[] byteArr = new byte[byteNum];
		
		int curInt = 0;
		for(int j=0, k=0; j<intArr.length; j++, k+=4 ){
			curInt = intArr[j];
			byteArr[k] =   (byte) ((curInt >>> 24) & 0xFF);
			byteArr[k+1] = (byte) ((curInt >>> 16) & 0xFF);
			byteArr[k+2] = (byte) ((curInt >>> 8) & 0xFF);
			byteArr[k+3] = (byte) ((curInt >>> 0) & 0xFF);
		}
		
		return byteArr;
		
	}
	
	public static void main(String[] args) throws IOException {
		
//		TypeService typeService = new TypeService();
//		
//		int[] intArr = new int[]{1,2,Integer.MIN_VALUE};
//		byte[] byteArr = typeService.convertIntArrToByteArr(intArr);
//		
//		File file = new File( "C:/Users/dell/Desktop/IT解决方案/aa.txt");
//		RandomAccessFile r = new RandomAccessFile(file, "rw");
//		r.write(byteArr);
//		r.close();
//		
//		System.out.println( Arrays.toString( typeService.convertByteArrToIntArr(byteArr)) );
		
//		byte b = (byte) 254;
//		System.out.println( (int)b );
//		System.out.println(Byte.MAX_VALUE);
//		System.out.println(Byte.MIN_VALUE);
	}
}


 

转载于:https://www.cnblogs.com/java-source/archive/2011/11/01/2604382.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值