六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 262|回复: 0

java char and UTF

[复制链接]

升级  68%

8

主题

8

主题

8

主题

童生

Rank: 1

积分
34
 楼主| 发表于 2013-1-14 23:44:52 | 显示全部楼层 |阅读模式
java中的char 占两个字节,默认使用UNICODE?转换成文件保存时,根据字符范围写入到文件中。
0开使的字符为asc码的128个字符,用1byte保存;x<=0X7F
110开始的字符用2byte保存;0X7F<x<0X8F
111开始的字符用3byte保存。x>0X8F
不多说,上一段hsqldb里的代码。
public static int stringToUTFBytes(String str,                                       HsqlByteArrayOutputStream out) {        int strlen = str.length();        int c,            count  = 0;        if (out.count + strlen + 8 > out.buffer.length) {            out.ensureRoom(strlen + 8);        }        char[] arr = str.toCharArray();        for (int i = 0; i < strlen; i++) {            c = arr[i];            if (c >= 0x0001 && c <= 0x007F) {                out.buffer[out.count++] = (byte) c;                count++;            } else if (c > 0x07FF) {                out.buffer[out.count++] = (byte) (0xE0 | ((c >> 12) & 0x0F));                out.buffer[out.count++] = (byte) (0x80 | ((c >> 6) & 0x3F));                out.buffer[out.count++] = (byte) (0x80 | ((c >> 0) & 0x3F));                count                   += 3;            } else {                out.buffer[out.count++] = (byte) (0xC0 | ((c >> 6) & 0x1F));                out.buffer[out.count++] = (byte) (0x80 | ((c >> 0) & 0x3F));                count                   += 2;            }            if (out.count + 8 > out.buffer.length) {                out.ensureRoom(strlen - i + 8);            }        }        return count;    } 
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表