wallyone 2015-05-18 14:08 采纳率: 25%
浏览 3797
已采纳

如何将string转换为byte

开发中需要这样的功能,将String str = "0f8adffb11dc" 转换为byte[] byteText = { 0x0f, 0x8a, 0xdf, 0xfb,0x11, 0xdc};请问如何实现,谢谢!

  • 写回答

4条回答 默认 最新

  • danielinbiti 2015-05-18 14:49
    关注
     public class Test {
        public static byte uniteBytes(byte src0, byte src1) { 
            byte _b0 = Byte.decode("0x" + new String(new byte[]{src0})).byteValue(); 
            _b0 = (byte)(_b0 << 4); 
            byte _b1 = Byte.decode("0x" + new String(new byte[]{src1})).byteValue(); 
            byte ret = (byte)(_b0 ^ _b1); 
            return ret; 
        } 
        public static byte[] HexString2Bytes(String src){ 
            byte[] ret = new byte[src.length()/2]; 
            byte[] tmp = src.getBytes(); 
            for(int i=0; i<src.length()/2; i++){ 
                ret[i] = uniteBytes(tmp[i*2], tmp[i*2+1]); 
            } 
            return ret; 
        } 
        public static void main(String[] args) {
            byte[] byteText = { 0x0f, (byte) 0x8a, (byte) 0xdf, (byte) 0xfb,0x11, (byte) 0xdc};
            byte[] ret = Test.HexString2Bytes("0f8adffb11dc");
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?