现在的位置: 首页 > 综合 > 正文

Java 将byte[] 与int类型互相转换

2018年04月13日 ⁄ 综合 ⁄ 共 906字 ⁄ 字号 评论关闭
    在使用TCP socket进行编写文件传输协议的时候,找Java中,可以使用BufferedOutputStream 和 BufferedInputStream来缓冲输出和输入的数据,但是,这里有个问题,BufferedOutputStream类的write函数和BufferedInputStream类的read函数都是使用byte[]作为放置数据的区域,因此,需要将其他的一些数据类型转化为byte数组类型。

    在设置通信协议的时候,有时需要将数据包中的数据部分的大小也放在包中进行传送,因此,首先考虑如何将int类型转化为byte数组类型,以及如何将byte数组类型转化为int类型。
    由于Java的内置类型的具体所占的字节数都是规定好的(并不像C++那样,不同的实现中,相同的类型的长度是不同),byte的长度为1个字节,而int类型的长度为4个字节。因此,对于int类型来说,可以使用一个有4个元素的byte数组来表示。
    下面是具体的代码:
/**
 * 
 */
package com.sheng.File;


/**
 * @author sheng
 *
 */
public class Converter 
{
	/**
	 * 
	 * @param Input The input int used to be converted to byte array
	 * @return The byte array 
	 */
	public static byte[] ConvertIntToByteArray(int Input)
	{
		byte[] result = new byte[4];
		
		for (int Index = 0; Index < 4; Index++)
		{
			result[Index] = (byte)(Input % 32);
			Input = Input / 32;
		}
		
		return result;
	}
	
	
	
	/**
	 * 
	 * @param Input
	 * @return
	 */
	public static int ConvertByteArrayToInt(byte[] Input)
	{
		int result = 0;
		
		for (int Index = 0; Index < 4; Index++)
		{
			result = result * 32 + Input[3 - Index];
		}
		
		return result;
	}
	


}











抱歉!评论已关闭.