2021-09-02 java 汉字转String 大端变小端

2021-09-06  本文已影响0人  fjasmin
 public static String LedStrSend(String chinese_str){
        //字符 方工前施 意全注安
        /**
         * 字符转换
         */

        String new_led_str = exchange(exchange(exchange(exchange(exchange(exchange(chinese_str,0,2),0,3),0,1),4,5),5,7),6,7);

        // System.out.println(new_led_str);

        //unicode 转 String
        String unicode_str = (HexUtil.unicodeEncode(new_led_str)).replace("\\"+"u","");

        //转 unicode String 转 byte[]
        byte[] buff_unicode_str = HexUtil.fromHexString(unicode_str);


        //大端
        System.out.println(bytesToHexString(buff_unicode_str));

        //大端转小端
        int sum1 = 0,sum2 =0,sum = 0;
        String str = "";
        for (int i = 0 ; i < buff_unicode_str.length;i++){
            if (i % 2 != 1)
            {
                //高字节
                sum1 = buff_unicode_str[i] << 8;
            }else {
                //低字节
                sum2 = buff_unicode_str[i] & 0xff;
            }

            if (i % 2 == 1){
                sum = sum1 + sum2;
                str += bytesToHexString(int2ByteArrayLittle(sum));
            }

        }
        //对调成功
        System.out.println(str);
        return str;
    }

 /**
     * 字符串内位置交换
     * @param target 目标字符串
     * @param pos1 位置1
     * @param pos2 位置2
     * @return 交换位置1 和位置2 后得到的目标字符串(StringIndexOutOfBounds 返回原字符串)
     */
    public static String exchange(String target,int pos1, int pos2){
        if(pos2<pos1){
            int temp = pos2;
            pos2 = pos1;
            pos1 = temp;
        }
        if(pos1 == pos2||pos2 >= target.length()||pos1 <= -1){
            return target;
        }
        String str1 = target.substring(pos1,pos1+1);
        String str2 = target.substring(pos2,pos2+1);
        StringBuffer buf = new StringBuffer(target.length());
        return buf.append(target.substring(0,pos1)).append(str2)
                .append(target.substring(pos1+1,pos2)).append(str1)
                .append(target.substring(pos2+1)).toString();
    }

上一篇下一篇

猜你喜欢

热点阅读