Java和C/C++交互的字节工具类

 package cn.com.insigma.utils;

import java.util.Calendar;
import java.util.Date;

/**
 * 字节工具类
 * @author jingxuan
 */
public class ByteUtils {
/**
* int convert byte[]
* @param n
* @return
*/
public static byte[] int2Bytes(int n) {
byte[] b = new byte[4];
b[3] = (byte) (n & 0xff);
b[2] = (byte) (n >> 8 & 0xff);
b[1] = (byte) (n >> 16 & 0xff);
b[0] = (byte) (n >> 24 & 0xff);
return b; 
}

/**
* byte[] convert int
* @param b
* @return
*/
public static int bytes2Int(byte b[]) {
return b[3] & 0xff | (b[2] & 0xff) << 8 | (b[1] & 0xff) << 16
| (b[0] & 0xff) << 24;
}

/**
* float to byte[]
* @param f
* @return
*/
public static byte[] float2Bytes(float f) {

int fbit = Float.floatToIntBits(f);
byte[] b = new byte[4];
for (int i = 0; i < 4; i++) {
b[i] = (byte) (fbit >> (24 - i * 8));
}

int len = b.length;
byte[] dest = new byte[len];
System.arraycopy(b, 0, dest, 0, len);

byte temp;
for (int i = 0; i < len / 2; ++i) {
temp = dest[i];
dest[i] = dest[len - i - 1];
dest[len - i - 1] = temp;
}

return dest;

}

// 时1字节,分1字节,秒1字节,年2字节,月1字节,日1字节, 预留1字节
/**
* 日期转成8字节byte[]
* @param date
* @return
*/
public static byte[] date2Bytes(Date date) {
byte[] b = new byte[8];
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);

// 按时、分、秒、年、月、日顺序
b[0] = int2OneByte(hour); // 1字节
b[1] = int2OneByte(minute);// 1字节
b[2] = int2OneByte(second);// 1字节
System.arraycopy(int2TwoBytes(year), 0, b, 3, 2);// 年,2字节
b[5] = int2OneByte(month+1);// 1字节
b[6] = int2OneByte(day);// 1字节
//b[7] 保留一字节
return b;
}
public static long bytes2Long(byte[] b)  { 
       long iOutcome = 0; 
       byte bLoop; 
       for (int i = 0; i <b.length; i++)  { 
           bLoop = b[i];
           iOutcome += ((long)(bLoop & 0x000000ff)) << (8 * i); 
       } 
       return iOutcome; 
   }
 
public static byte[] longtoBytes(long l){
byte[] byteArray = new byte[8];
        for (int i=0; i<8; i++){
            byteArray[i] = new Long(l & 0xFF).byteValue();
            l >>= 8;
        }    
        return byteArray;
    }

/**
* int convert 1 byte
* @param num
* @return
*/
public static byte int2OneByte(int num) {
return (byte) (num & 0xff);
}

/**
* int convert byte[](length = 2)
* @param num
* @return
*/
public static byte[] int2TwoBytes(int num) {
byte[] b = new byte[2];
b[1] = (byte) (num & 0xff);
b[0] = (byte) (num >> 8 & 0xff);
return b;
}
/**
* short convert byte[]
* @param b
* @return
*/
public static short bytes2Short(byte[] b){
return (short)(b[1] & 0xff | (b[0] & 0xff) << 8);
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值