ByteUtil字节工具类

简介: ByteUtil字节工具类
import java.io.IOException;
import java.math.BigInteger;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

import org.springframework.util.StringUtils;

public class ByteUtil {
    public static byte[] uintToBytes(long value) {
        byte[] src = new byte[4];
        src[3] = ((byte) (int) (value >> 24 & 0xFF));
        src[2] = ((byte) (int) (value >> 16 & 0xFF));
        src[1] = ((byte) (int) (value >> 8 & 0xFF));
        src[0] = ((byte) (int) (value & 0xFF));
        return src;
    }

    public static byte[] uint16ToBytes(int value) {
        byte[] src = new byte[2];
        src[1] = ((byte) (value >> 8 & 0xFF));
        src[0] = ((byte) (value & 0xFF));
        return src;
    }

    public static byte[] uint8ToBytes(short value) {
        byte[] src = new byte[1];
        src[0] = ((byte) (value & 0xFF));
        return src;
    }

    /**
     * ascii 转 十六进制
     * 
     * @param str
     * @return
     */
    public static String convertStringToHex(String str) {

        char[] chars = str.toCharArray();

        StringBuffer hex = new StringBuffer();
        for (int i = 0; i < chars.length; i++) {
            hex.append(Integer.toHexString((int) chars[i]));
        }

        return hex.toString();
    }

    /**
     * 十六进制转 ascii
     * 
     * @param hex
     * @return
     */
    public static String convertHexToString(String hex) {

        StringBuilder sb = new StringBuilder();
        StringBuilder temp = new StringBuilder();

        // 49204c6f7665204a617661 split into two characters 49, 20, 4c...
        for (int i = 0; i < hex.length() - 1; i += 2) {

            // grab the hex in pairs
            String output = hex.substring(i, (i + 2));
            // convert hex to decimal
            int decimal = Integer.parseInt(output, 16);
            // convert the decimal to character
            sb.append((char) decimal);

            temp.append(decimal);
        }

        return sb.toString();
    }

    /**
     * 十六进制字符串高低位互换
     * 
     * 如:12345678 -> 78563412
     * 00 5f 8d c2
     * c28d5f00
     * @param str
     * @return float
     */
    public static float hexStrTofloat(String str) {
        try {
            String s = str.substring(6, 8) + str.substring(4, 6) + str.substring(2, 4) + str.substring(0, 2);
            return Float.intBitsToFloat(new BigInteger(s,16).intValue());
        } catch (NumberFormatException e) {
            e.printStackTrace();
            System.err.println("errrrr..");
            return 0L;
        }
    }

    public static float hexStrTofloat1(String str) {
        try {
            int i = Integer.parseInt(str, 16);
            byte byte4 = (byte) (i & 0xff);
            byte byte3 = (byte) ((i & 0xff00) >> 8);
            byte byte2 = (byte) ((i & 0xff0000) >> 16);
            byte byte1 = (byte) ((i & 0xff000000) >> 24); // 拼装成 "高字节在后,低字节在前"的格式
            int realint = (byte1 & 0xff) << 0 | (byte2 & 0xff) << 8 | (byte3 & 0xff) << 16 | (byte4 & 0xff) << 24;
            return Float.intBitsToFloat(realint);
        } catch (NumberFormatException e) {
            System.err.println("errrrr..");
            return 0L;
        }

    }

    public static int bytesToInt(byte[] src, int startPos) {
        if ((src == null) || (src.length <= 0) || (src.length < startPos + 4) || (startPos < 0)) {
            return -1;
        }
        int result = (int) ((src[(startPos + 3)] & 0xFF) * 16777216 + (src[(startPos + 2)] & 0xFF) * 65536L
                + (src[(startPos + 1)] & 0xFF) * 256L + (src[startPos] & 0xFF));
        return result;
    }

    public static int bytesToIntHL(byte[] src, int startPos, int len) {
        if ((src == null) || (src.length <= 0) || (src.length < startPos + len) || (startPos < 0)) {
            return -1;
        }
        int result = 0;
        for (int i = 0; i < len; i++) {
            result += (int) ((src[(startPos + i)] & 0xFF) * (1 << (len - 1 - i) * 8));
        }
        return result;
    }

    public static void printHexString(byte[] b) {
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            System.out.print(hex.toUpperCase() + " ");
        }
        System.out.println();
    }

    /**
     * 字节数组转为十六进制字符串
     * 
     * @param src
     * @return
     */
    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if ((src == null) || (src.length <= 0)) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    public static String bytesToDecString(byte[] src) {
        if ((src == null) || (src.length <= 0)) {
            return null;
        }
        int result = (int) ((src[3] & 0xFF) * 16777216 + (src[2] & 0xFF) * 65536L + (src[1] & 0xFF) * 256L
                + (src[0] & 0xFF));
        return Integer.toString(result);
    }

    public static String bytesToHexString(byte[] src, int len) {
        StringBuilder stringBuilder = new StringBuilder("");
        StringBuilder temp = new StringBuilder("");
        if ((src == null) || (src.length <= 0)) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            if (v != 0) {
                String hv = Integer.toHexString(v);
                StringBuilder temp1 = new StringBuilder("");
                if (hv.length() < 2) {
                    temp1.append(0);
                }
                temp1.append(hv);
                temp1.append(temp);
                temp = temp1;
            }
        }
        if (len / 2 > temp.length()) {
            String result = temp.toString();
            for (int k = 0; k < (len - result.length()) / 2; k++) {
                stringBuilder.append("00");
            }
            stringBuilder.append(result);
        } else {
            stringBuilder = temp;
        }
        return stringBuilder.toString();
    }

    public static String bytesToDecString(byte[] src, int len) {
        if ((src == null) || (src.length <= 0)) {
            return null;
        }
        int result = (int) (src[3] * 16777216 + src[2] * 65536L + src[1] * 256L + src[0]);
        String temp = Integer.toString(result);
        if (temp.length() < len) {
            StringBuilder finalString = new StringBuilder("");
            for (int k = 0; k < len - temp.length(); k++) {
                finalString.append(0);
            }
            finalString.append(result);
            return finalString.toString();
        }
        return temp;
    }

    public static float byte2float(byte[] b, int index) {
        int l = b[(index + 0)];
        l &= 0xFF;
        l = (int) (l | b[(index + 1)] << 8);
        l &= 0xFFFF;
        l = (int) (l | b[(index + 2)] << 16);
        l &= 0xFFFFFF;
        l = (int) (l | b[(index + 3)] << 24);
        return Float.intBitsToFloat(l);
    }

    public static int ASCIIToInt(byte[] b, int len) {
        int result = 0;
        for (int i = 0; i < len; i++) {
            char temp = (char) b[i];
            int i_temp;
            switch (temp) {
            case 'A':
                i_temp = 10;
                break;
            case 'B':
                i_temp = 11;
                break;
            case 'C':
                i_temp = 12;
                break;
            case 'D':
                i_temp = 13;
                break;
            case 'E':
                i_temp = 14;
                break;
            case 'F':
                i_temp = 15;
                break;
            default:
                i_temp = Integer.valueOf(temp).intValue();
            }
            result = i_temp + result * 16;
        }
        return result;
    }

    public static String ASCIIToString(byte[] b, int len) {
        String result = "";
        for (int i = 0; i < len; i++) {
            result = result + (char) b[i];
        }
        return result;
    }


    /**
     * 将16进制字符串转换为byte[]
     * 
     * @param str
     * @return
     */
    public static byte[] toBytes(String str) {
        if (str == null || str.trim().equals("")) {
            return new byte[0];
        }

        byte[] bytes = new byte[str.length() / 2];
        for (int i = 0; i < str.length() / 2; i++) {
            String subStr = str.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) Integer.parseInt(subStr, 16);
        }

        return bytes;
    }

    public static byte get_byte(int head_offset, PortContext pPort) {
        int len = pPort.headcount;
        if ((head_offset > 0) || (head_offset < -len)) {
            return 0;
        }
        return pPort.g_recb_head[(len + head_offset)];
    }

    public static int get_u16(int head_offset, PortContext pPort) {
        byte byte1 = get_byte(head_offset - 1, pPort);
        byte byte2 = get_byte(head_offset - 2, pPort);
        int data0 = (byte1 & 0xFF) << 8 | byte2 & 0xFF;
        return data0;
    }

    public static long get_u32(int head_offset, PortContext pPort) {
        byte byte1 = get_byte(head_offset - 1, pPort);
        byte byte2 = get_byte(head_offset - 2, pPort);
        byte byte3 = get_byte(head_offset - 3, pPort);
        byte byte4 = get_byte(head_offset - 4, pPort);
        long data0 = (byte1 & 0xFF) << 24 | (byte2 & 0xFF) << 16 | (byte3 & 0xFF) << 8 | byte4 & 0xFF;
        return data0;
    }

    public static int get_pos(int head_offset, PortContext pPort) {
        int len = pPort.headcount;
        if ((-head_offset < len) && (head_offset <= 0)) {
            return len + head_offset;
        }
        return 0;
    }
/**
     *
     * 带符号的16进制字符串转float
     * */
    public static float SigneHexToFloat(String str) {
        String s = str.substring(2, 4) + str.substring(0, 2);
        float x = (float)Integer.valueOf(s, 16).shortValue();
        return x;
    }
    /**
     * 有符号16进制转10进制
     * @param strHex
     * @return
     */
    public static int signedHexToDec(String strHex){
        if(strHex.length()==0){
            return 0;
        }
        int x = 0;
        //带符号十六进制转换十进制
        String fristNum = strHex.substring(0, 1);
        String hexStr2Byte = parseHexStr2Byte(fristNum);
        String flag = hexStr2Byte.substring(0, 1);
        if("1".equals(flag)){
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < strHex.length(); i++) {
                String num = strHex.substring(i, i+1);
                int decNum = Integer.parseInt(num,16);
                int a = decNum^15;
                sb.append(intToHex(a));
            }
            x = -Integer.parseInt(sb.toString(),16)-1;
        }else{
            x = Integer.parseInt(strHex,16);
        }

        return x;

    }

    //十进制转16进制
    private static String intToHex(int n) {
        StringBuffer s = new StringBuffer();
        String a;
        char []b = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        while(n != 0){
            s = s.append(b[n%16]);
            n = n/16;
        }
        a = s.reverse().toString();
        return a;
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static String parseHexStr2Byte(String hexStr) {
        if (hexStr.length() == 0) {
            return null;
        }
        int sint=Integer.valueOf(hexStr, 16);
        //十进制在转换成二进制的字符串形式输出!
        String bin=Integer.toBinaryString(sint);
        for (int i = bin.length(); i < 4; i++) {
            bin = "0"+bin;
        }
        return bin;
    }
}
目录
相关文章
|
4月前
|
Java
Java系列之 字符串和字节互转
这篇文章是关于Java中字符串和字节之间互转的方法,包括使用`getBytes()`方法将字符串转换为字节数组,以及使用String构造方法将字节数组转换回字符串。
|
7月前
|
传感器 数据采集 网络协议
Java串口通信:从十六进制字符串到字节数组的正确转换与发送
Java串口通信:从十六进制字符串到字节数组的正确转换与发送
332 4
|
7月前
|
Java
Java中如何将接口返回的字节串转为文件
Java中如何将接口返回的字节串转为文件
76 0
|
Java
Java字节缓冲流
Java字节缓冲流
50 0
java202303java学习笔记第三十五天字节输入流循环读取
java202303java学习笔记第三十五天字节输入流循环读取
56 0
【Java】文件操作篇(二)字节输入流、字节输出流及常用子类(下)
文章目录 写在前面 1 FileInputStream文件输入流 1.1 构造方法与常用方法摘要 1.2 文件输入案例 2 FileOutputStream文件输出流 2.1 构造方法与常用方法摘要 2.2 文件输出案例 2.3 文件拷贝 3 处理流 3.1 BufferedInputStream介绍 3.2 BufferedOutputStream介绍
【Java】文件操作篇(二)字节输入流、字节输出流及常用子类(下)
|
存储 Java
【Java】文件操作篇(二)字节输入流、字节输出流及常用子类(上)
文章目录 写在前面 1 FileInputStream文件输入流 1.1 构造方法与常用方法摘要 1.2 文件输入案例 2 FileOutputStream文件输出流 2.1 构造方法与常用方法摘要 2.2 文件输出案例 2.3 文件拷贝 3 处理流 3.1 BufferedInputStream介绍 3.2 BufferedOutputStream介绍
【Java】文件操作篇(二)字节输入流、字节输出流及常用子类(上)
java152-字节缓冲输出流
java152-字节缓冲输出流
105 0
java152-字节缓冲输出流