---
title: "java中计算汉字的字节数"
author: "fgh2011"
date: "2012-08-08T11:40:29Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2012-08-08T11:40:29Z"
id: 1625139
url: "https://fgh2011.iteye.com/blog/1625139"
---

中文并不一定是占两个字节的，具体占多少字节是跟具体的编码方式相关的。
比如说：GB2312、GBK、GB18030 编码是占用两个字节的，但是 UTF-8 编码的话至少需要占用三个字节。
有一个简单方法，就是把大于 0xff 的字符都作为两个字符（当然是在 GBK 环境下）



Java code 
public static int count(String str) {
    if(str == null || str.length == 0) {
        return 0;
    }
    int count = 0;
    char chs = str.toCharArray();
    for(int i = 0; i < chs.length; i++) {
        count += (chs* > 0xff) ? 2 : 1;
    }
    return count;
}


或者你直接使用 int len = str.getBytes("gbk");

上面代码假设你的数据库编码格式是 GBK 的，而不是 UTF-8 的，如果是 UTF-8 的话，上面的代码无效！

1字节等于8比特，一个字母是1字节，而一个汉字要用2个字节。

一个汉字=2个字符