亂碼的轉換

2021-06-26 07:56:27 字數 2138 閱讀 7604

最近在做乙個反饋功能,把資料反饋到對方公司**,我公司是gbk編碼,對方公司是utf-8編碼。因此,我需要將gbk編碼資料轉換成utf-8編碼資料,這樣對方**才不會亂碼。最簡單的方法是將

的contentcharset設定為utf-8;如果contentcharset是gbk並且又不想設定為utf-8,那麼就需要將資料轉換成utf-8編碼再發到對方**。

問題出現:gbk轉utf-8時,奇數個中文會亂碼,偶數個中文不會亂碼。

三個中文 

public static void encodeerror() throws unsupportedencodingexception /*我來??*/ 前面三個中文,後面乙個中文,都是奇數

public static void encodeerror2() throws unsupportedencodingexception  

system.out.println();

for (byte b : utf8.getbytes())  

} /*

-26 -120 -111 -26 -99 -91 -28 -70 -122 

-26 -120 -111 -26 -99 -91 -28 -70 63 ! 

*/ 注意最後乙個位元組不同,上面一行才是正確的utf-8編碼。那麼為什麼下面一行最後乙個位元組是63,而不是-122呢?這就是導致亂碼的原因所在。

gbk編碼是乙個中文2個位元組,而utf-8編碼是乙個中文3個位元組,當我們呼叫getbytes("utf-8")方法時,會通過計算來增加位元組,使得從gbk的2個位元組變成utf-8對應的3個位元組。因此,上例3個中文輸出了9個位元組。

這裡講一下怎麼通過計算增加位元組,不深究的讀者可以跳過此段。為了醒目,直接用**講解

public static void gbk2utf() throws unsupportedencodingexception  

//增加位,達到到24位3個位元組

sb.insert(0, "1110"); 

sb.insert(8, "10");

sb.insert(16, "10"); 

fullbyte[i*3] = integer.valueof(sb.substring(0, 8), 2).bytevalue();//

二進位制字串建立整型 

fullbyte[i*3+1] = integer.valueof(sb.substring(8, 16), 2).bytevalue();

fullbyte[i*3+2] = integer.valueof(sb.substring(16, 24), 2).bytevalue();

} @, n* v4 r3 n0 t

//模擬utf-8編碼的**顯示

system.out.println(new string(fullbyte,"utf-8")); 

}現在我們來找出最後乙個位元組是63,而不是-122的原因。 

public static void analyze2() throws unsupportedencodingexception  

/*鎴戞潵浜? 

*/ 因為檔案是gbk編碼,new string(utfbytes)預設就是new string(utfbytes,"gbk")。它會2個位元組2個位元組地轉換成字元,當位元組是奇數時最後1個位元組轉字元就會計算錯誤,然後直接賦予最後這個字元為?,對應

ascii

**就是63。

解決問題 

保證位元組正確才是硬道理。當呼叫getbytes("utf-8")轉換成

位元組陣列

後,建立

iso-8859-1

編碼的字串,iso-8859-1編碼是乙個位元組對應乙個字元,因此不會使最後乙個位元組錯誤。

public static void correctencode() throws unsupportedencodingexception

system.out.println(); 

//模擬utf-8編碼的**顯示

system.out.println(new string(iso.getbytes("iso-8859-1"),"utf-8"));

}/* 

-26 -120 -111 -26 -99 -91 -28 -70 -122 

我來了*/

php 轉換中文亂碼,解決php中文亂碼轉換問題

php中文亂碼轉換的解決辦法 1 設定編碼為 header content type text html charset utf 8 2 使用 mb convert encoding 等函式進行轉換。php 中文輸出亂碼和轉碼問題 1.header content type text html ch...

能夠轉換中文亂碼的JavaBean

public class charactorencoding public charactorencoding public string tostring string str string text if str null equals str try text new string str.g...

php 轉換中文亂碼,php中文編碼轉換問題

php中文編碼轉換的方法 1 使用iconv函式,為 string iconv string in string out string str 2 使用 mb convert encoding 函式。php中文編碼轉換的方法 一 iconvstring iconv string in charset...