美文网首页
Hex字符串与Bytes数组互相转换(应用场景:虹软byte数组

Hex字符串与Bytes数组互相转换(应用场景:虹软byte数组

作者: CoderInsight | 来源:发表于2023-09-25 17:26 被阅读0次
    1. 基于Bytes数据与字符串之间的互相转换;
    2. 灵活的设置截取的长度,方便剔除一些标志的字节;
    /**  
     * @author wangyq  
     */
    public class CustomHexUtils {  
      
        /**  
         * 根据传入的字节数组,返回字符串  
         * @param length 截取指定长度的数组  
         */  
        public static String getBytes2String(byte[] b, int length) {  
            StringBuilder stringBuffer = new StringBuilder(512);  
            for (int i = 0; i < length; ++i) {  
                String hex = Integer.toHexString(b[i] & 0xFF);  
                if (hex.length() == 1) {  
                    hex = '0' + hex;  
                }  
                stringBuffer.append(hex.toUpperCase());  
            }  
            return stringBuffer.toString();  
        }  
        
        /**  
         * 将字符串转化为二进制byte数组  
         * @param hex 字符串  
         */  
        public static byte[] hexStringToByte(String hex) {  
            int len = (hex.length() / 2);  
            byte[] result = new byte[len];  
            char[] singleChar = hex.toCharArray();  
            for (int i = 0; i < len; i++) {  
                int pos = i * 2;  
                result[i] = (byte) (toByte(singleChar[pos]) << 4 | toByte(singleChar[pos + 1]));  
            }  
            return result;  
        }  
        
        /**  
         * 字符转byte  
         * @param c 字符  
         * @return byte  
         */    
      private static byte toByte(char c) {
            return (byte) "0123456789ABCDEF".indexOf(c);  
        }  
    }
    

    相关文章

      网友评论

          本文标题:Hex字符串与Bytes数组互相转换(应用场景:虹软byte数组

          本文链接:https://www.haomeiwen.com/subject/malcbdtx.html