標籤:
1位元組(Byte)=8bit
java的基本類型
| 類型 |
所佔位元組 |
| byte |
1 |
| short |
2 |
| int |
4 |
| long |
8 |
| float |
4 |
| double |
8 |
| char |
2 |
String中字母和漢字所佔字元是不一樣的,並且與編碼有關
英文字母:A
| 位元組數 |
編碼 |
| 1 |
GB2312 |
| 1 |
GBK |
| 1 |
GB18030 |
| 1 |
ISO-8859-1 |
| 1 |
UTF-8 |
| 4 |
UTF-16 |
| 2 |
UTF-16BE |
| 2 |
UTF-16-LE |
中文漢字:我
| 位元組數 |
編碼 |
| 1 |
GB2312 |
| 2 |
GBK |
| 2 |
GB18030 |
| 1 |
ISO-8859-1 |
| 3 |
UTF-8 |
| 4 |
UTF-16 |
| 2 |
UTF-16BE |
| 2 |
UTF-16-LE |
附錄:計算String位元組數的代碼
package com.dingrui.stringbytelength;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.UnsupportedEncodingException;import org.dozer.loader.api.FieldDefinition;public class StringByteLength {/* * GB2312 GBK GB18030 ISO-8859-1 UTF-8 UTF-16 UTF-16BE UTF-16LE */public static void main(String[] args) throws IOException {String s1 = "a";String s2 = "龘";System.out.println(s1 + " GB2312 " + s1.getBytes("GB2312").length);System.out.println(s1 + " GBK " + s1.getBytes("GBK").length);System.out.println(s1 + " GB18030 " + s1.getBytes("GB18030").length);System.out.println(s1 + " ISO-8859-1 " + s1.getBytes("ISO-8859-1").length);System.out.println(s1 + " UTF-8 " + s1.getBytes("UTF-8").length);System.out.println(s1 + " UTF-16 " + s1.getBytes("UTF-16").length);System.out.println(s1 + " UTF-16BE " + s1.getBytes("UTF-16BE").length);System.out.println(s1 + " UTF-16LE " + s1.getBytes("UTF-16LE").length);System.out.println("---------------");System.out.println(s2 + " GB2312 " + s2.getBytes("GB2312").length);System.out.println(s2 + " GBK " + s2.getBytes("GBK").length);System.out.println(s2 + " GB18030 " + s2.getBytes("GB18030").length);System.out.println(s2 + " ISO-8859-1 " + s2.getBytes("ISO-8859-1").length);System.out.println(s2 + " UTF-8 " + s2.getBytes("UTF-8").length);System.out.println(s2 + " UTF-16 " + s2.getBytes("UTF-16").length);System.out.println(s2 + " UTF-16BE " + s2.getBytes("UTF-16BE").length);System.out.println(s2 + " UTF-16LE " + s2.getBytes("UTF-16LE").length);}/** * 將轉碼後的文字寫入檔案,通過編輯器開啟測試,確認寫入的是相應編碼 * * @param bytes * @throws IOException */public void writeFile(byte[] bytes) throws IOException {String path = StringByteLength.class.getResource("/").getPath();System.out.println(path);String file_path = path + "charsetFile";File file = new File(file_path);if (!file.exists()) {file.createNewFile();}FileOutputStream out = new FileOutputStream(file);out.write(bytes);out.close();}}
java中各種資料類型佔用位元組數