nio-Netty-字节的工具封装

31 篇文章 0 订阅
24 篇文章 0 订阅
 /**
     * 字符串转数组,需要传入数组的位数
     *
     * @param n   byte数组位数
     * @param str 待转字符串
     * @return byte[]
     */
    public static byte[] str2bytes(int n, String str) {
        byte[] temp = new byte[n];

        byte[] strByte = str.getBytes(Charset.forName("GBK"));

        int length = n >= strByte.length ? strByte.length : n;

        System.arraycopy(strByte, 0, temp, 0, length);

        return temp;
    }

package com.common.util;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class ByteUtil {
	private static  int  INT8_MASK  = 0xFF;
	private static  int  INT16_MASK = 0xFFFF;
	private static  long INT32_MASK = 0xFFFFFFFFL;
	
	public static  long[] DECIMALISM = { 1000000000000000000L,
        100000000000000000L, 10000000000000000L, 1000000000000000L,
        100000000000000L, 10000000000000L, 1000000000000L, 100000000000L,
        10000000000L, 1000000000L, 100000000L, 10000000L, 1000000L,
        100000L, 10000L, 1000L, 100L, 10L, 1L };
	 /**
	  * 取ByteBuffer中一个字节,转换成带符号的int
	  * @param buf 
	  * @return int
	  * @throws Exception
	  */


    public static  int int8(ByteBuffer buf) {
        return buf.get();
    }

    /**
     * 取ByteBuffer中一个字节,转换成无符号的int
     * @param buf
     * @return int
     * @throws Exception
     */
    public static  int uint8(ByteBuffer buf) {
        return buf.get() & INT8_MASK;
    }

    /**
     * 取ByteBuffer中两个字节,转换成int
     * @param buf
     * @return int
     * @throws Exception
     */
    public static  int int16(ByteBuffer buf) {
        return buf.getShort();
    }

    /**
     * 取ByteBuffer中两个字节,转换成无符号的int
     * @param buf
     * @return int
     * @throws Exception
     */
    public static  int uint16(ByteBuffer buf) {
        return buf.getShort() & INT16_MASK;
    }

    /**
     * 取ByteBuffer中四个字节,转换成int
     * @param buf
     * @return int
     * @throws Exception
     */
    public static  long int32(ByteBuffer buf) {
        return buf.getInt();
    }
    /**
     * 取ByteBuffer中四个字节,转换成无符号的int
     * @param buf
     * @return int
     * @throws Exception
     */
    public static  long uint32(ByteBuffer buf) {
        return buf.getInt() & INT32_MASK;
    }

   /**
    * 取ByteBuffer中八个字节,转换成long
    * @param buf
    * @return long
    * @throws Exception
    */
    public static  long int64(ByteBuffer buf) {
        return buf.getLong();
    }

    /**
     * 将ByteBuffer转换成String,utf8编码<br>
     * 如果读取到0,则不会继续读取
     * @param buf
     * @return
     * @throws Exception
     */
    public static  String string(ByteBuffer buf) {
        List<Byte> list = new ArrayList<Byte>(10);
        byte b = -1;
        while ((b = buf.get()) != 0) {
            list.add(b);
        }
        byte[] bs = new byte[list.size()];
        for (int i = 0; i < bs.length; i++) {
            bs[i] = list.get(i);
        }
        return new String(bs);
    }

    /**
     * 取length长度的ByteBuffer转换成String,utf8编码
     * @param buf 
     * @param length 
     * @return
     * @throws Exception
     */
    public static  String string(ByteBuffer buf, int length) {
        byte[] bs = new byte[length];
        buf.get(bs);
        return new String(bs);
    }

    /**
     * 取length长度的ByteBuffer转换成String,gbk编码
     * @param buf
     * @param length
     * @return
     * @throws Exception
     */
    public static  String gbk(ByteBuffer buf, int length) throws Exception{
        byte[] bs = new byte[length];
        buf.get(bs);
        int real = 0;
        for (real = 0; real < bs.length && bs[real] != 0; real++);
        return new String(bs, 0, real, "GBK");
    }

    /**
     * 将ByteBuffer转换成String,gbk编码<br>
     * 如果读取到0,则不会继续读取
     * @param buf
     * @return
     * @throws Exception
     */
    public static  String gbk(ByteBuffer buf) throws Exception{
        byte[] bs = new byte[1024];
        int index = 0;
        while (buf.hasRemaining()) {
            byte b = buf.get();
            if (b == 0) {
                break;
            }
            bs[index++] = b;
        }
        return new String(bs, 0, index, "GBK");
    }

    /**
     * 从ByteBuffer取出length长度的字节<br>
     * 如果ByteBuffer中剩余字节不够,全部取出
     * @param buf
     * @param length
     * @return
     * @throws Exception
     */
    public static  byte[] bytes(ByteBuffer buf, int length) {
        byte[] bs = new byte[length];
        buf.get(bs);
        return bs;
    }

    /**
     * ByteBuffer向后移动length个字节<br>
     * 如果ByteBuffer剩余字节小于length,不做处理
     * @param buf
     * @param length
     * @throws Exception
     */
    public static  void skip(ByteBuffer buf, int length){
        if (buf.remaining() >= length) {
            buf.position(buf.position() + length);
        }
    }
    /**
     * 从ByteBuffer中取出length长度的字节<br>
     * 字节不够全部取出,然后转换成GBK编码字符串,同时去掉空格
     * @param buf
     * @param lenght
     * @return
     * @throws Exception
     */
    public static  String removeSpace(ByteBuffer buf, int lenght) throws Exception{
        byte space = 0x20;
        byte[] bs = new byte[lenght];
        buf.get(bs);
        int real = 0;
        for (; real < bs.length && bs[real] != space; real++);      
        return new String(bs, 0, real, "GBK");
    }
   
    /**
     * 
     * 从ByteBuffer中取出length长度的字节<br>
     * 字节不够全部取出,然后转换成asc码拼接成的字符串
     * @param buf
     * @param lenght
     * @return
     * @throws Exception
     */
    public static  String ascii(ByteBuffer buf, int lenght) {
        byte[] bs = new byte[lenght];
        buf.get(bs);
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < bs.length; i++) {
            buffer.append((char)bs[i]);
        }
        return buffer.toString();
    }
    
    /**
     * 从ByteBuffer中取出length长度的字节<br>
     * 字节不够全部取出,然后转换成长整型,如取出的字节为0x17,则返回17而不是23
     * @param buf
     * @param len
     * @return
     * @throws Exception
     */
    public static  long bcd(ByteBuffer buf, int len) {
        byte[] bs = new byte[len];
        buf.get(bs);
        long result = 0;
        for (int i = 0; i < len; i++) {
            result += DECIMALISM[DECIMALISM.length - len * 2 + i * 2 + 1]
                    * (bs[i] & 0x0F);
            result += DECIMALISM[DECIMALISM.length - len * 2 + i * 2]
                    * ((bs[i] >> 4) & 0x0F);
        }
        return result;
    }
    
    /**
     * 从ByteBuffer中取出length长度的字节<br>
     * 字节不够全部取出,然后转换成bcd码的字符串,如取出的字节为0x17,则返回17而不是23
     * @param buf
     * @param len
     * @return
     * @throws Exception
     */
    public static  String bcdString(ByteBuffer buf, int len) {
        byte[] bs = new byte[len];
        buf.get(bs);
        String str = "";
        for (int i = 0; i < bs.length; i++) {
            byte e = bs[i];
            str += Integer.toHexString((e >> 4) & 0x0f);
            str += Integer.toHexString(e & 0x0f);
        }
        return str;
    }

    /**
     * 从ByteBuffer取6个字节,每个字节为无符号的整形<br>
     * 转成年月日时分秒的转成date,数组中格式为yymmddhhmmss
     * @param buf
     * @return
     * @throws Exception
     */
    public static Date date(ByteBuffer buf) {
        int year = uint8(buf) + 2000;
        int month = uint8(buf);
        int date = uint8(buf);
        int hour = uint8(buf);
        int minute = uint8(buf);
        int second = uint8(buf);

        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, date, hour, minute, second);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    /**
     * 从ByteBuffer取6个字节,每个字节为bcd码<br>
     * 转成年月日时分秒的date,年份2017为17
     * @param buf
     * @return
     * @throws Exception
     */
    public static  Date bcdDate(ByteBuffer buf) {
        int year = (int) (bcd(buf, 1) + 2000);
        int month = (int) bcd(buf, 1);
        int date = (int) bcd(buf, 1);
        int hour = (int) bcd(buf, 1);
        int minute = (int) bcd(buf, 1);
        int second = (int) bcd(buf, 1);

        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, date, hour, minute, second);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    /**
     * 从ByteBuffer取7个字节,每个字节为bcd码<br>
     * 转成年月日时分秒的date,年份2017为2017
     * @param buf
     * @return
     * @throws Exception
     */
    public static  Date bcdDateFullYear(ByteBuffer buf) {
        int year = (int) bcd(buf, 2);
        int month = (int) bcd(buf, 1);
        int date = (int) bcd(buf, 1);
        int hour = (int) bcd(buf, 1);
        int minute = (int) bcd(buf, 1);

        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, date, hour, minute);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }
    /**
     * 从ByteBuffer取3个字节(时分秒都为0),每个字节为bcd码<br>
     * 转成年月日时分秒的date,年份2017为17
     * @param buf
     * @return
     * @throws Exception
     */
    public static  Date bcdDateNoHMS(ByteBuffer buf) {
    	int year = (int) (bcd(buf, 1) + 2000);
        int month = (int) bcd(buf, 1);
        int date = (int) bcd(buf, 1);

        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, date);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }
    
    /**
     * 从ByteBuffer取4个字节(时分秒都为0),每个字节为bcd码<br>
     * 转成年月日时分秒的date,年份2017为2017
     * @param buf
     * @return
     * @throws Exception
     */
    public static  Date bcdDateFullYearNoMS(ByteBuffer buf) {
        int year = (int) bcd(buf, 2);
        int month = (int) bcd(buf, 1);
        int date = (int) bcd(buf, 1);
        int hour = (int) bcd(buf, 1);

        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, date, hour, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }
    
    /**
     * 把data转成byte数组,放入byteBuffer中
     * @param buf
     * @param date
     * @throws Exception
     */
    public static  void putDate(ByteBuffer buf, Date date) {
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR) - 2000;
        int month = c.get(Calendar.MONTH) + 1;
        int day = c.get(Calendar.DAY_OF_MONTH);
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
        int second = c.get(Calendar.SECOND);
        byte[] bs = new byte[] { (byte) year, (byte) month, (byte) day,
                (byte) hour, (byte) minute, (byte) second };
        buf.put(bs);
    }

    /**
     * 把GBK编码的String转成byte数组,放入ByteBuffer中
     * @param buf
     * @param str
     * @throws Exception
     */
    public static  void putString(ByteBuffer buf, String str)
            throws Exception {
        byte[] bs = str.getBytes("GBK");
        buf.put(bs);
        buf.put((byte) 0);
    }

    /**
     * 把gbk编码字符串转成byte数组放入ByteBuffer中
     * @param buf
     * @param str
     * @throws Exception
     */
    public static  void putGbkString(ByteBuffer buf, String str) throws Exception{
		byte[] bs = null;
		bs = str.getBytes("GBK");
		buf.put(bs);
    }

   /**
    * 将一个long转成bcd放入bytebuffer中<br>
    * len表示bcd的长度
    * @param buf
    * @param l
    * @param len
    * @throws Exception
    */
    public static  void putBcd(ByteBuffer buf, long l, int len) {
        for (int i = DECIMALISM.length - len * 2; i < DECIMALISM.length; i += 2) {
            byte b = 0;
            b = (byte) ((l / DECIMALISM[i] % 10) << 4);
            b |= (l / DECIMALISM[i + 1] % 10);
            buf.put(b);
        }
    }
    /**
     * 把date转成bcd,放入bytebuffer中<br>
     * bcd的格式为yymmddhhmmss
     * @param buf
     * @param date
     * @throws Exception
     */
    public static  void putBcdDate(ByteBuffer buf, Date date){
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        putBcd(buf, c.get(Calendar.YEAR) - 2000, 1);
        putBcd(buf, c.get(Calendar.MONTH) + 1, 1);
        putBcd(buf, c.get(Calendar.DAY_OF_MONTH), 1);
        putBcd(buf, c.get(Calendar.HOUR_OF_DAY), 1);
        putBcd(buf, c.get(Calendar.MINUTE), 1);
        putBcd(buf, c.get(Calendar.SECOND), 1);
    }
    
    /**
     * 把字节数组按16进制转字符串
     * @param buf
     * @return
     * @throws Exception
     */
    public static String hex(byte[] buf){
    	StringBuilder sb = new StringBuilder();
    	 String table = "0123456789ABCDEF";
    	for (int i = 0; i < buf.length; i++) {
    		sb.append(table.charAt(buf[i] >> 4 & 0x0f));
    		sb.append(table.charAt(buf[i] & 0x0f));
    	}
    	return sb.toString();
    }
	/**
	 * byte[]转二进制字符串
	 * @param buf
	 * @return
	 */
	public static String bytes2Hex(byte[] buf) {
        if (null == buf) {
            return "";
        }
        
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < buf.length; ++i) {
            s.append(String.format("%02X ", buf[i]));
        }
        s.deleteCharAt(s.length()-1);
        
        return s.toString().replaceAll(" ", "");
    }
    /**
     * convert hex string to byte array
     * @param msg
     * @return
     */
    public static byte[] hex2Byte(String msg) {
 	   
 	   if (msg == null || msg.isEmpty()){
 		   return null;
 	   }
 	   String data = msg.toUpperCase();
 	   if ((data.length() % 2) != 0){
 		   data = msg + "0";
 	   }
 	   int len = data.length() / 2;
 	   
 	   ByteBuffer buf = ByteBuffer.allocate(len);
 	   for (int i = 0; i < data.length(); i += 2){
 		   int cl = hexChar2Int(data.codePointAt(i));
 		   int cr = hexChar2Int(data.codePointAt(i + 1));
 		   byte b = (byte) ((cl << 4 & 0xF0) | (cr & 0x0F));
 		   buf.put(b);
 	   }
 	   
 	   return buf.array();
    }
    
    /**
     * ASCII code to hex index 'A' -> 10, 'B' -> 11...
     * @param c
     * @return
     */
     public static int hexChar2Int(int c){
  	   if (c >= 0x30 && c <= 0x39){
  		   return c - 0x30;
  	   }
  	   if (c >= 0x41 && c <= 0x46){
  		   return c - 0x37;
  	   }
  	   return 0;
     }
    
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值