Byte変換

3376 ワード

/**
	 *  
	 * 
	 * @param val
	 * @return
	 */
	public static byte[] int2ByteArr(int val, short lenght)
	{
		byte[] result = new byte[lenght];
		int temp = val;
		for (int i = lenght - 1; i >= 0; i--)
		{
			result[i] = (byte) (temp & 0xFF);
			temp = temp >> 8;
		}
		return result;
	}
/**
	 *  
	 * 
	 * @param val
	 * @return
	 */
	public static byte[] short2ByteArr(short val, short lenght)
	{
		byte[] result = new byte[lenght];
		short temp = val;
		for (int i = lenght - 1; i >= 0; i--)
		{
			result[i] = (byte) (temp & 0xFF);
			temp = (short) (temp >> 8);
		}
		return result;
	}
/**
	 *  
	 * 
	 * @param bytes
	 * @param offset
	 * @param lenght
	 * @return
	 */
	public static long bytesToLong(byte[] bytes, int offset, short lenght)
	{
		long addr = 0l;
		for (int i = lenght - 1; i >= 0; i--)
		{
			if (i == lenght - 1)
			{
				addr = (long) (bytes[offset + i] & 0xFF);
			}
			else
			{
				addr |= ((long) (bytes[offset + i] & 0xFF) << (lenght - i - 1) * 8);
			}
		}
		return addr;
	}
/**
	 *  
	 * 
	 * @param bytes
	 * @param offset
	 * @param lenght
	 * @return
	 */
	public static int bytesToInt(byte[] bytes, int offset, short lenght)
	{
		int addr = 0;
		for (int i = lenght - 1; i >= 0; i--)
		{
			if (i == lenght - 1)
			{
				addr = (bytes[offset + i] & 0xFF);
			}
			else
			{
				addr |= ((bytes[offset + i] & 0xFF) << (lenght - i - 1) * 8);
			}
		}
		return addr;
	}
/**
	 *  
	 * 
	 * @param bytes
	 * @param offset
	 * @param lenght
	 * @return
	 */
	public static short bytesToShort(byte[] bytes, int offset, short lenght)
	{
		short addr = 0;
		for (int i = lenght - 1; i >= 0; i--)
		{
			if (i == lenght - 1)
			{
				addr = (short) (bytes[offset + i] & 0xFF);
			}
			else
			{
				addr |= ((bytes[offset + i] & 0xFF) << (lenght - i - 1) * 8);
			}
		}
		return addr;
	}
/**
	 *  
	 */
	public static byte[] append(byte[] arr1, byte[] arr2)
	{
		if (arr1 == null)
		{
			return arr2;
		}
		if (arr2 == null)
		{
			return arr1;
		}
		arr1 = Arrays.copyOf(arr1, arr1.length + arr2.length);
		System.arraycopy(arr2, 0, arr1, arr1.length - arr2.length, arr2.length);
		return arr1;
	}

	/**
	 *  
	 */
	public static boolean equals(byte[] arr1, byte[] arr2)
	{
		if (arr1 == null)
		{
			return arr2 == null;
		}
		if (arr2 == null || arr1.length != arr2.length)
		{
			return false;
		}
		for (int i = 0; i < arr1.length; i++)
		{
			if (arr1[i] != arr2[i])
			{
				return false;
			}
		}
		return true;
	}