开发者社区> 问答> 正文

java里怎字符串“0xDE"转为字节型的0xDE

把从SD卡里取出来的字符串“0x03 0x04 0x05"转为(byte)0x03 (byte)0x03

展开
收起
爵霸 2016-06-16 10:23:38 3092 0
2 条回答
写回答
取消 提交回答
  • 可以直接使用guava的BaseEncoding.base16().decode方法进行解析
    _2

    2019-07-17 19:40:25
    赞同 展开评论 打赏
  • public static byte[] hexStringToBytes(String hexString) {  
            if (hexString == null || hexString.equals("")) {  
                return null;  
            }  
            hexString = hexString.toUpperCase();  
            if(hexString.indexOf("0X")>=0) hexString=hexString.replace("0X", "");
            int length = hexString.length() / 2;  
            char[] hexChars = hexString.toCharArray();  
            byte[] d = new byte[length];  
            for (int i = 0; i < length; i++) {  
                int pos = i * 2;  
                d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));  
            }  
            return d;  
        }  
        private static byte charToByte(char c) {  
            return (byte) "0123456789ABCDEF".indexOf(c);  
        }  
        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            byte[] by = hexStringToBytes("0x030x040x05");
            byte[] by2 = new byte[]{(byte) 0x03,(byte) 0x04,(byte) 0x05};
                    //这两个by和by2是一致的
        }
    2019-07-17 19:40:25
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载