码迷,mamicode.com
首页 > 编程语言 > 详细

一些算法的整理

时间:2015-07-06 12:12:00      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

BA21转换成21BA的算法

String str1 = "BA21";                // 十六进制字符串     
String str2 = "";                                // 反转后的字符串
for (int i = str1.length() - 2; i >= 0; i = i - 2)
<span style="white-space:pre">    </span>{
           str2 += str1.substring(i,i+2);
    }
System.out.println(str2);

Java合并两个数组

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
   public static void main(String args[]) {
      String a[] = { "A", "E", "I" };
      String b[] = { "O", "U" };
      List list = new ArrayList(Arrays.asList(a));
      list.addAll(Arrays.asList(b));
      Object[] c = list.toArray();
      System.out.println(Arrays.toString(c));
   }
}

 

char[]和byte[]的互转

// char转byte
private byte[] getBytes (char[] chars) {
   Charset cs = Charset.forName ("UTF-8");
   CharBuffer cb = CharBuffer.allocate (chars.length);
   cb.put (chars);
                 cb.flip ();
   ByteBuffer bb = cs.encode (cb);
  
   return bb.array();

 }

// byte转char

private char[] getChars (byte[] bytes) {
      Charset cs = Charset.forName ("UTF-8");
      ByteBuffer bb = ByteBuffer.allocate (bytes.length);
      bb.put (bytes);
                 bb.flip ();
       CharBuffer cb = cs.decode (bb);
  
   return cb.array();

}

其他的一些,注释部分有详细的说明:

public static double[] getYData(String string) {
        string = string.trim().replace(" ", "");
        double[] data = new double[string.length() / 4];// 这里最好判断下字符串数据的长度
        for (int i = 0; i < data.length; i++) {
            data[i] = parseHex(string.substring(4 * i, 4 * i + 4));
        }
        return data;
    }

    /**
     * 将接收到的字节数组转化成16进制的字符串
     * 
     * @param b
     * @return
     * @throws Exception
     */
    public static String getHexString(byte[] b) throws Exception {
        String result = "";
        for (int i = 0; i < b.length; i++) {
            result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
        }
        return result;
    }

    /**
     * 将字符串转化成byte[]
     * 
     * @param hexString
     * @return
     */
    public static byte[] getByteArray(String hexString) {
        return new BigInteger(hexString, 16).toByteArray();
    }

    /**
     * 将十六进制的字符转变成十进制整型数据
     * 
     * @param str
     * @return
     */
    public static int parseHex(String str) {
        int result = 0;
        try {
            int temp = Integer.parseInt(str.trim(), 16);
            result = temp;
        } catch (NumberFormatException e) {
            long ltemp = Long.parseLong(str.trim(), 16);
            result = (int) ltemp;
        }
        return result;
    }

 



 

一些算法的整理

标签:

原文地址:http://www.cnblogs.com/sowhat4999/p/4439863.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!