关闭

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

标签: java与CC++数据交互字节工具类
518人阅读 评论(0) 收藏 举报
分类:
 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);
}
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:9286次
    • 积分:287
    • 等级:
    • 排名:千里之外
    • 原创:19篇
    • 转载:1篇
    • 译文:0篇
    • 评论:0条
    文章分类