java中字符跟字节转换 总结

String and Byte

由于近期程序中经常要用到进制转换,于是把这些方法抽取,方便以后直接使用
    /**
     * 字符串1345642123 → byte []l={1,3,4,5,6,4,2,1,2,3}
     **/
    public static byte[] StringtoSingleByte(String sPhone) {

        byte[] bPhone = sPhone.getBytes();
        for (int i = bPhone.length - 1; i >= 0; i--) {
            bPhone[i] -= (byte) '0';
        }
        return bPhone;
    }

    /**
     * 字符串124312 → byte []hexbyte={0x12,0x43,0x12}
     **/
    public static byte[] StringtoHexBytes(String src) {
        if (null == src || 0 == src.length()) {
            return null;
        }
        byte[] ret = new byte[src.length() / 2];
        byte[] tmp = src.getBytes();
        // System.out.println("tmp="+Arrays.toString(tmp));
        /*
         * int length = 0; if (tmp.length % 2 != 0) { length=(tmp.length+1)/2; }
         * length=tmp.length;
         */
        for (int i = 0; i < (tmp.length / 2); i++) {
            ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
        }

        return ret;
    }

    public static byte uniteBytes(byte src0, byte src1) {
        byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 }))
                .byteValue();
        _b0 = (byte) (_b0 << 4);
        // System.out.println("_b0="+_b0);
        byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 }))
                .byteValue();
        byte ret = (byte) (_b0 ^ _b1);
        return ret;
    }

    /**
     * 字符串 124312 → byte []hexbyte={12,43,12}
     **/
    public static byte[] StringtoByte(String a){
        int length = a.length();
        byte []BYTE = new byte[a.length()/2];
        if(length%2!=0){
            a="0"+a;
            BYTE=new byte[a.length()/2];
            length = a.length();
        }
        for(int i=length;i>1;i=i-2){
            BYTE[i/2-1]=Byte.parseByte(a.substring(i-2, i));
        }

    return BYTE;
    }

    public static void main(String[] args) {
        String a ="12345678";
        byte [] b=StringtoHexBytes(a);
        System.out.println(Arrays.toString(b));
    }
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值