package com.yqw.java.util;
/**
* 数字转换工具
*/
public class MathUtils {
/**
* short转byte
*/
public static byte[] toBytes(short s)
{
return new byte[] { (byte)(s & 0x00FF), (byte)((s & 0xFF00) >> 8) };
}
/**
* unsigned short转byte
*/
public static byte[] unsignedShortToBytes(int s)
{
return new byte[] { (byte)(s & 0x000000FF),
(byte)((s & 0x0000FF00) >> 8) };
}
/**
* int转byte
*/
public static byte[] toBytes(int s)
{
return new byte[] { (byte) (s & 0x000000FF),
(byte)((s & 0x0000FF00) >> 8),
(byte)((s & 0x00FF0000) >> 16),
(byte)((s & 0xFF000000) >> 24) };
}
/**
* byte转int
*/
public static int toInt(byte[] b)
{
return b[0] & 0xff | (b[1] & 0xff) << 8| (b[2] & 0xff) << 16
| (b[3] & 0xff<< 24);
}
/**
* byte转long
*/
public static long toUnsignedInt(byte[] b)
{
return b[0]& 0xff | (b[1] & 0xff) << 8| (b[2] & 0xff) << 16
| (b[3] << 24);
}
/**
* byte转short
*/
public static short toShort(byte[] b)
{
// return (short) (b[0] << 24 | (b[1] & 0xff) << 16) ;
return (short) (((b[1] << 8) | b[0] & 0xff));
}
/**
* byte转unsigned short
*/
public static int toUnsignedShort(byte[] b)
{
return (b[0] << 24 | (b[1] & 0xff) << 16) ;
}
/**
* Assume the long is used as unsigned int
* @param s
* @return
*/
public static byte[] unsignedIntToBytes(long s)
{
return new byte[] { (byte) (s & 0x00000000000000FF),
(byte)((s & 0x000000000000FF00) >> 8),
(byte)((s & 0x0000000000FF0000) >> 16),
(byte)((s & 0x00000000FF000000) >> 24) };
}
/**
* float转换byte
*
* @param x
* @param index
*/
public static byte[] putFloat(float x) {
byte[] b = new byte[4];
int l = Float.floatToIntBits(x);
for (int i = 0; i < 4; i++) {
b[i] = new Integer(l).byteValue();
l = l >> 8;
}
return b;
}
/**
* 通过byte数组取得float
*
* @param b
* @return
*/
public static float getFloat(byte[] b) {
int l;
l = b[0];
l &= 0xff;
l |= ((long) b[1] << 8);
l &= 0xffff;
l |= ((long) b[2] << 16);
l &= 0xffffff;
l |= ((long) b[3] << 24);
return Float.intBitsToFloat(l);
}
}