要写让全世界人看的代码

Peter 发表于 2010-01-04 00:00:00

收藏: QQ书签 del.icio.us 订阅: Google 抓虾

关于编码

Peter 发表于 2008-11-17 13:35:19

标题 谈谈Unicode编码,简要解释UCS、UTF、BMP、BOM等名词 选择自 fmddlmyy 的 Blog
关键字 谈谈Unicode编码,简要解释UCS、UTF、BMP、BOM等名词

这是一篇程序员写给程序员的趣味读物。所谓趣味是指可以比较轻松地了解一些原来不清楚的概念,增进知识,类似于打RPG游戏的升级。整理这篇文章的动机是两个问题:

问题一:
使用Windows记事本的“另存为”,可以在GBK、Unicode、Unicode big endian和UTF-8这几种编码方式间相互转换。同样是txt文件,Windows是怎样识别编码方式的呢?

我很早前就发现Unicode、Unicode big endian和UTF-8编码的txt文件的开头会多出几个字节,分别是FF、FE(Unicode),FE、FF(Unicode big endian),EF、BB、BF(UTF-8)。但这些标记是基于什么标准呢?

问题二:
最近在网上看到一个ConvertUTF.c,实现了UTF-32、UTF-16和UTF-8这三种编码方式的相互转换。对于Unicode(UCS2)、GBK、UTF-8这些编码方式,我原来就了解。但这个程序让我有些糊涂,想不起来UTF-16和UCS2有什么关系。
查了查相关资料,总算将这些问题弄清楚了,顺带也了解了一些Unicode的细节。写成一篇文章,送给有过类似疑问的朋友。本文在写作时尽量做到通俗易懂,但要求读者知道什么是字节,什么是十六进制。

0、big endian和little endian
big endian和little endian是CPU处理多字节数的不同方式。例如“汉”字的Unicode编码是6C49。那么写到文件里时,究竟是将6C写在前面,还是将49写在前面?如果将6C写在前面,就是big endian。还是将49写在前面,就是little endian。

“endian”这个词出自《格列佛游记》。小人国的内战就源于吃鸡蛋时是究竟从大头(Big-Endian)敲开还是从小头(Little-Endian)敲开,由此曾发生过六次叛乱,其中一个皇帝送了命,另一个丢了王位。

我们一般将endian翻译成“字节序”,将big endian和little endian称作“大尾”和“小尾”。

1、字符编码、内码,顺带介绍汉字编码
字符必须编码后才能被计算机处理。计算机使用的缺省编码方式就是计算机的内码。早期的计算机使用7位的ASCII编码,为了处理汉字,程序员设计了用于简体中文的GB2312和用于繁体中文的big5。

GB2312(1980年)一共收录了7445个字符,包括6763个汉字和682个其它符号。汉字区的内码范围高字节从B0-F7,低字节从A1-FE,占用的码位是72*94=6768。其中有5个空位是D7FA-D7FE。

GB2312支持的汉字太少。1995年的汉字扩展规范GBK1.0收录了21886个符号,它分为汉字区和图形符号区。汉字区包括21003个字符。2000年的GB18030是取代GBK1.0的正式国家标准。该标准收录了27484个汉字,同时还收录了藏文、蒙文、维吾尔文等主要的少数民族文字。现在的PC平台必须支持GB18030,对嵌入式产品暂不作要求。所以手机、MP3一般只支持GB2312。

从ASCII、GB2312、GBK到GB18030,这些编码方法是向下兼容的,即同一个字符在这些方案中总是有相同的编码,后面的标准支持更多的字符。在这些编码中,英文和中文可以统一地处理。区分中文编码的方法是高字节的最高位不为0。按照程序员的称呼,GB2312、GBK到GB18030都属于双字节字符集 (DBCS)。

有的中文Windows的缺省内码还是GBK,可以通过GB18030升级包升级到GB18030。不过GB18030相对GBK增加的字符,普通人是很难用到的,通常我们还是用GBK指代中文Windows内码。

这里还有一些细节:

GB2312的原文还是区位码,从区位码到内码,需要在高字节和低字节上分别加上A0。

在DBCS中,GB内码的存储格式始终是big endian,即高位在前。

GB2312的两个字节的最高位都是1。但符合这个条件的码位只有128*128=16384个。所以GBK和GB18030的低字节最高位都可能不是1。不过这不影响DBCS字符流的解析:在读取DBCS字符流时,只要遇到高位为1的字节,就可以将下两个字节作为一个双字节编码,而不用管低字节的高位是什么。

2、Unicode、UCS和UTF
前面提到从ASCII、GB2312、GBK到GB18030的编码方法是向下兼容的。而Unicode只与ASCII兼容(更准确地说,是与ISO-8859-1兼容),与GB码不兼容。例如“汉”字的Unicode编码是6C49,而GB码是BABA。

Unicode也是一种字符编码方法,不过它是由国际组织设计,可以容纳全世界所有语言文字的编码方案。Unicode的学名是"Universal Multiple-Octet Coded Character Set",简称为UCS。UCS可以看作是"Unicode Character Set"的缩写。

根据维基百科全书(http://zh.wikipedia.org/wiki/)的记载:历史上存在两个试图独立设计Unicode的组织,即国际标准化组织(ISO)和一个软件制造商的协会(unicode.org)。ISO开发了ISO 10646项目,Unicode协会开发了Unicode项目。

在1991年前后,双方都认识到世界不需要两个不兼容的字符集。于是它们开始合并双方的工作成果,并为创立一个单一编码表而协同工作。从Unicode2.0开始,Unicode项目采用了与ISO 10646-1相同的字库和字码。

目前两个项目仍都存在,并独立地公布各自的标准。Unicode协会现在的最新版本是2005年的Unicode 4.1.0。ISO的最新标准是10646-3:2003。

UCS规定了怎么用多个字节表示各种文字。怎样传输这些编码,是由UTF(UCS Transformation Format)规范规定的,常见的UTF规范包括UTF-8、UTF-7、UTF-16。

IETF的RFC2781和RFC3629以RFC的一贯风格,清晰、明快又不失严谨地描述了UTF-16和UTF-8的编码方法。我总是记不得IETF是Internet Engineering Task Force的缩写。但IETF负责维护的RFC是Internet上一切规范的基础。

3、UCS-2、UCS-4、BMP

UCS有两种格式:UCS-2和UCS-4。顾名思义,UCS-2就是用两个字节编码,UCS-4就是用4个字节(实际上只用了31位,最高位必须为0)编码。下面让我们做一些简单的数学游戏:

UCS-2有2^16=65536个码位,UCS-4有2^31=2147483648个码位。

UCS-4根据最高位为0的最高字节分成2^7=128个group。每个group再根据次高字节分为256个plane。每个plane根据第3个字节分为256行 (rows),每行包含256个cells。当然同一行的cells只是最后一个字节不同,其余都相同。

group 0的plane 0被称作Basic Multilingual Plane, 即BMP。或者说UCS-4中,高两个字节为0的码位被称作BMP。

将UCS-4的BMP去掉前面的两个零字节就得到了UCS-2。在UCS-2的两个字节前加上两个零字节,就得到了UCS-4的BMP。而目前的UCS-4规范中还没有任何字符被分配在BMP之外。

4、UTF编码

UTF-8就是以8位为单元对UCS进行编码。从UCS-2到UTF-8的编码方式如下:

UCS-2编码(16进制) UTF-8 字节流(二进制)
0000 - 007F 0xxxxxxx
0080 - 07FF 110xxxxx 10xxxxxx
0800 - FFFF 1110xxxx 10xxxxxx 10xxxxxx

例如“汉”字的Unicode编码是6C49。6C49在0800-FFFF之间,所以肯定要用3字节模板了:1110xxxx 10xxxxxx 10xxxxxx。将6C49写成二进制是:0110 110001 001001, 用这个比特流依次代替模板中的x,得到:11100110 10110001 10001001,即E6 B1 89。

读者可以用记事本测试一下我们的编码是否正确。

UTF-16以16位为单元对UCS进行编码。对于小于0x10000的UCS码,UTF-16编码就等于UCS码对应的16位无符号整数。对于不小于0x10000的UCS码,定义了一个算法。不过由于实际使用的UCS2,或者UCS4的BMP必然小于0x10000,所以就目前而言,可以认为UTF-16和UCS-2基本相同。但UCS-2只是一个编码方案,UTF-16却要用于实际的传输,所以就不得不考虑字节序的问题。

5、UTF的字节序和BOM
UTF-8以字节为编码单元,没有字节序的问题。UTF-16以两个字节为编码单元,在解释一个UTF-16文本前,首先要弄清楚每个编码单元的字节序。例如收到一个“奎”的Unicode编码是594E,“乙”的Unicode编码是4E59。如果我们收到UTF-16字节流“594E”,那么这是“奎”还是“乙”?

Unicode规范中推荐的标记字节顺序的方法是BOM。BOM不是“Bill Of Material”的BOM表,而是Byte Order Mark。BOM是一个有点小聪明的想法:

在UCS编码中有一个叫做"ZERO WIDTH NO-BREAK SPACE"的字符,它的编码是FEFF。而FFFE在UCS中是不存在的字符,所以不应该出现在实际传输中。UCS规范建议我们在传输字节流前,先传输字符"ZERO WIDTH NO-BREAK SPACE"。

这样如果接收者收到FEFF,就表明这个字节流是Big-Endian的;如果收到FFFE,就表明这个字节流是Little-Endian的。因此字符"ZERO WIDTH NO-BREAK SPACE"又被称作BOM。

UTF-8不需要BOM来表明字节顺序,但可以用BOM来表明编码方式。字符"ZERO WIDTH NO-BREAK SPACE"的UTF-8编码是EF BB BF(读者可以用我们前面介绍的编码方法验证一下)。所以如果接收者收到以EF BB BF开头的字节流,就知道这是UTF-8编码了。

Windows就是使用BOM来标记文本文件的编码方式的。

6、进一步的参考资料
本文主要参考的资料是 "Short overview of ISO-IEC 10646 and Unicode" (http://www.nada.kth.se/i18n/ucs/unicode-iso10646-oview.html)。

"Understanding Unicode A general introduction to the Unicode Standard" (http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&item_id=IWS-Chapter04a)
"Character set encoding basics Understanding character set encodings and legacy encodings" (http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&item_id=IWS-Chapter03)

收藏: QQ书签 del.icio.us 订阅: Google 抓虾

rmi

Peter 发表于 2008-07-01 15:22:21

C:\MyWorkspace\pritace\src\rmi>rmic -classpath ../ rmi.HelloServer
和class的编译稍微有点不一样呢,呵呵
收藏: QQ书签 del.icio.us 订阅: Google 抓虾

新闻工作者……冷静 冷静

Peter 发表于 2008-06-17 09:21:00

昨天在电视里听到报道地震时一个孩子的勇敢,是朝廷台的。
报道是这样说的,他不知道有坍塌的危险,奋不顾身的坚持营救。
这……实在是……太……勇敢……了……啊…………

不知道有坍塌的危险是傻吧,或者就算真的不知道,也不能用奋不顾身啊,就算真的是奋不顾身,和不知道坍塌的危险这个前提也挂不上钩吧

本来好好的一个事迹,怎么听起来变得像是骂人了
……
收藏: QQ书签 del.icio.us 订阅: Google 抓虾

nio example

Peter 发表于 2008-06-11 15:32:58

client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

/**
 * @author ylkang
 *
 */
public class Client {
 public SocketChannel client = null;
 public InetSocketAddress isa = null;
 public RecvThread rt = null;
 private String host;
 private int port;

 public Client(String host, int port) {
  this.host = host;
  this.port = port;
 }

 public void makeConnection() {
//  String proxyHost = "192.168.254.212";
//  String proxyPort = "1080";
//  System.getProperties().put("socksProxySet", "true");
//  System.getProperties().put("socksProxyHost", proxyHost);
//  System.getProperties().put("socksProxyPort", proxyPort);
  int result = 0;
  try {
   client = SocketChannel.open();
   isa = new InetSocketAddress(InetAddress.getLocalHost(), port);
   client.connect(isa);
   client.configureBlocking(false);
   receiveMessage();
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  long begin = System.currentTimeMillis();
  sendMessage();
  long end = System.currentTimeMillis();
  long userTime = end - begin;
  System.out.println("use tiem: " + userTime);
  try {
   interruptThread();
   client.close();
   System.exit(0);
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

 public int sendMessage() {
  System.out.println("Inside SendMessage");
  String msg = null;
  ByteBuffer bytebuf;
  int nBytes = 0;
  try {
   msg = "It's message from client!";
   System.out.println("msg is " + msg);
   bytebuf = ByteBuffer.wrap(msg.getBytes());
   for (int i = 0; i < 1000; i++) {
    nBytes = client.write(ByteBuffer.wrap(((new String((bytebuf.array())) + i + "--")).getBytes()));
    System.out.println(i + " finished");
   }
   interruptThread();
   try {
    Thread.sleep(5000);
   } catch (Exception e) {
    e.printStackTrace();
   }
   client.close();
   return -1;
  } catch (IOException e) {
   e.printStackTrace();
  }
  return nBytes;
 }

 public void receiveMessage() {
  rt = new RecvThread("Receive THread", client);
  rt.start();
 }

 public void interruptThread() {
  rt.val = false;
 }

 public static void main(String args[]) {
  if (args.length < 2) {
   System.err.println("You should put 2 args: host,port");
  } else {
   String host = args[0];
   int port = Integer.parseInt(args[1]);
   Client cl = new Client(host, port);
   cl.makeConnection();
  }
  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  String msg;
 }

 public class RecvThread extends Thread {
  public SocketChannel sc = null;
  public boolean val = true;

  public RecvThread(String str, SocketChannel client) {
   super(str);
   sc = client;
  }

  public void run() {
   int nBytes = 0;
   ByteBuffer buf = ByteBuffer.allocate(2048);
   try {
    while (val) {
     while ((nBytes = nBytes = client.read(buf)) > 0) {
      buf.flip();
      Charset charset = Charset.forName("us-ascii");
      CharsetDecoder decoder = charset.newDecoder();
      CharBuffer charBuffer = decoder.decode(buf);
      String result = charBuffer.toString();
//      System.out.println("the server return: " + result);
      buf.flip();
     }
    }
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
}

server

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.Iterator;
import java.util.Set;

public class NonBlockingServer {
 public Selector sel = null;
 public ServerSocketChannel server = null;
 public SocketChannel socket = null;
 public int port = 4900;
 String result = null;

 public NonBlockingServer() {
  System.out.println("Inside default ctor");
 }

 public NonBlockingServer(int port) {
  System.out.println("Inside the other ctor");
  this.port = port;
 }

 public void initializeOperations() throws IOException, UnknownHostException {
  System.out.println("Inside initialization");
  sel = Selector.open();
  server = ServerSocketChannel.open();
  server.configureBlocking(false);
  InetAddress ia = InetAddress.getLocalHost();
  InetSocketAddress isa = new InetSocketAddress(ia, port);
  server.socket().bind(isa);
 }

 public void startServer() throws IOException {
  System.out.println("Inside startserver");
  initializeOperations();
  System.out.println("Abt to block on select()");
  SelectionKey acceptKey = server.register(sel, SelectionKey.OP_ACCEPT);
  while (acceptKey.selector().select() > 0) {
   Set readyKeys = sel.selectedKeys();
   Iterator it = readyKeys.iterator();
   while (it.hasNext()) {
    SelectionKey key = (SelectionKey) it.next();
    it.remove();
    if (key.isAcceptable()) {
//     System.out.println("Key is Acceptable");
     ServerSocketChannel ssc = (ServerSocketChannel) key
       .channel();
     socket = (SocketChannel) ssc.accept();
     socket.configureBlocking(false);
     SelectionKey another = socket.register(sel,
       SelectionKey.OP_READ | SelectionKey.OP_WRITE);
    }
    if (key.isReadable()) {
//     System.out.println("Key is readable");
     String ret = readMessage(key);
     if (ret.length() > 0) {
      writeMessage(socket, ret);
     }
    }
    if (key.isWritable()) {
//     System.out.println("THe key is writable");
     String ret = readMessage(key);
     socket = (SocketChannel) key.channel();
     if (result.length() > 0) {
      writeMessage(socket, ret);
     }
    }
   }
  }
 }

 public void writeMessage(SocketChannel socket, String ret) {
  System.out.println("Inside the loop");
  if (ret.equals("quit") || ret.equals("shutdown")) {
   return;
  }
  try {
   String s = "This is content from server!-----------------------------------------";
   System.out.println(ret);
   Charset set = Charset.forName("us-ascii");
   CharsetDecoder dec = set.newDecoder();
   CharBuffer charBuf = dec.decode(ByteBuffer.wrap(s.getBytes()));
   System.out.println(charBuf.toString());
   int nBytes = socket.write(ByteBuffer.wrap((charBuf.toString())
     .getBytes()));
   System.out.println("nBytes = " + nBytes);
   result = null;
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 public String readMessage(SelectionKey key) {
  int nBytes = 0;
  socket = (SocketChannel) key.channel();
  ByteBuffer buf = ByteBuffer.allocate(1024);
  try {
   nBytes = socket.read(buf);
   buf.flip();
   Charset charset = Charset.forName("us-ascii");
   CharsetDecoder decoder = charset.newDecoder();
   CharBuffer charBuffer = decoder.decode(buf);
   result = charBuffer.toString();
  } catch (IOException e) {
   e.printStackTrace();
  }
  return result;
 }

 public static void main(String args[]) {
  NonBlockingServer nb;
  if (args.length < 1) {
   nb = new NonBlockingServer();
  } else {
   int port = Integer.parseInt(args[0]);
   nb = new NonBlockingServer(port);
  }
  try {
   nb.startServer();
   System.out.println("the nonBlocking server is started!");
  } catch (IOException e) {
   e.printStackTrace();
   System.exit(-1);
  }
//  System.out.println("It's message from client!".getBytes());
 }
}

收藏: QQ书签 del.icio.us 订阅: Google 抓虾