2008年12月2日 星期二

how to get unicode/big5 code in java String

  1.  
  2. /*
  3. ConvertBig5Unicode.java
  4. print string in big5 and unicode
  5.  
  6. >javac ConvertBig5Unicode.java
  7. >java ConvertBig5Unicode
  8. 查詢字串: 今天天氣很好
  9. 查詢字串的統一碼 : 4eca 5929 5929 6c23 5f88 597d
  10. 查詢字串的大五碼 : a4b5 a4d1 a4d1 aef0 abdc a66e
  11. */
  12.  
  13. import java.io.File;
  14.  
  15. // 如何取得java字串之unicode及big5碼
  16. public class ConvertBig5Unicode
  17. {
  18. public static void main(String args[]) throws java.io.UnsupportedEncodingException
  19. {
  20. String query="今天天氣很好";
  21.  
  22. String unicode_query="";
  23. for(int i=0; i<=query.length()-1;i++)
  24. {
  25. if(query.charAt(i)>=0x100)
  26. unicode_query += Integer.toHexString(query.charAt(i)) + " ";
  27. else
  28. unicode_query += query.charAt(i);
  29. }
  30.  
  31. byte [] big5_stream=query.getBytes("big5");
  32. // java.io.UnsupportedEncodingException
  33.  
  34. String big5_query="";
  35. for(int i=0; i<=big5_stream.length-1;i++)
  36. {
  37. int b1,b2;
  38.  
  39. b1 = big5_stream[i];
  40. b2 = (i+1<=big5_stream.length-1)? big5_stream[i+1] : 0;
  41.  
  42. b1 = (b1>=0) ? b1 : 0x100+b1;
  43. b2 = (b2>=0) ? b2 : 0x100+b2;
  44.  
  45. //out.println("b1="+b1+",b2="+b2);
  46.  
  47. if((b1 >= 0xa1 && b1 <= 0xf9) && ((b2 >= 0x40 && b2 <= 0x7e) || (b2 >= 0xa1 && b2 <= 0xfe)))
  48. {
  49. big5_query += Integer.toHexString(b1) + Integer.toHexString(b2) + " ";
  50. i++;
  51. }
  52. else
  53. big5_query += (char) big5_stream[i];
  54. }
  55.  
  56. System.out.println("查詢字串: " + query);
  57. System.out.println("查詢字串的統一碼 : "+unicode_query);
  58. System.out.println("查詢字串的大五碼 : "+big5_query);
  59. }
  60. }

沒有留言: