Chinaunix首页 | 论坛 | 博客
  • 博客访问: 794563
  • 博文数量: 738
  • 博客积分: 7000
  • 博客等级: 少将
  • 技术积分: 5000
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-12 09:00
文章分类

全部博文(738)

文章存档

2011年(1)

2008年(737)

我的朋友

分类:

2008-09-12 09:06:50

  预备知识:

  1.字节和unicode

  内核是unicode的,就连class文件也是,但是很多媒体,包括文件/流的保存方式是使用字节流的。 因此要对这些字节流经行转化。char是unicode的,而byte是字节.Java中byte/char互转的函数在sun.io的包中间有。其中ByteToCharConverter类是中调度,可以用来告诉你,你用的Convertor。其中两个很常用的静态函数是。

  

   public static ByteToCharConverter getDefault() ;
  public static ByteToCharConverter getConverter(String encoding);

    
    如果你不指定converter,则系统会自动使用当前的Encoding,GB平台上用GBK,EN平台上用8859_1

  我们来就一个简单的例子:

  "你"的gb码是:0xC4E3 ,unicode是0x4F60

  你用:

  

   encoding="gb2312";
  byte b[]={(byte)'\u00c4',(byte)'\u00E3'};
  convertor=ByteToCharConverter.getConverter(encoding);
  char [] c=converter.convertAll(b);
  for(int i=0;i{
  ***.out.println(Integer.toHexString(c[i]));
  }

   打印出来是0x4F60

  但是如果使用8859_1的编码,打印出来是

  0x00C4,0x00E3

  例1

  反过来:

   encoding="gb2312";
  char c[]={'\u4F60'};
  convertor=ByteToCharConverter.getConverter(encoding);
  byte [] b=converter.convertAll(c);
  for(int i=0;i{
  ***.out.println(Integer.toHexString(b[i]));
  }

   
   打印出来是:0xC4,0xE3

  例2

  如果用8859_1就是0x3F,?号,表示无法转化

  很多中文问题就是从这两个最简单的类派生出来的。而却有很多类不直接支持把Encoding输入,这给我们带来诸多不便。很多程序难得用encoding了,直接用default的encoding,这就给我们移植带来了很多困难

  2.UTF-8

  UTF-8是和Unicode一一对应的,其实现很简单

  7位的Unicode: 0 _ _ _ _ _ _ _

  11位的Unicode: 1 1 0 _ _ _ _ _ 1 0 _ _ _ _ _ _

  16位的Unicode: 1 1 1 0 _ _ _ _ 1 0 _ _ _ _ _ _ 1 0 _ _ _ _ _ _

  21位的Unicode: 1 1 1 1 0 _ _ _ 1 0 _ _ _ _ _ _ 1 0 _ _ _ _ _ _ 1 0 _ _ _ _ _ _

  大多数情况是只使用到16位以下的Unicode:

  你"的gb码是:0xC4E3 ,unicode是0x4F60

  我们还是用上面的例子

  例1:0xC4E3的二进制:

  1 1 0 0 0 1 0 0 1 1 1 0 0 0 1 1

  由于只有两位我们按照两位的编码来排,但是我们发现这行不通,因为第7位不是0因此,返回"?"

【责编:Zenghui】

--------------------next---------------------

阅读(301) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~