中文字元ASCII碼和NSString相互轉換

2021-06-22 09:41:35 字數 2428 閱讀 6083

在xcode中,檔案以utf8格式儲存。因此,其中變數物件也是以utf8格式儲存。不同語言的utf8編碼不一樣,英文的utf8編碼和ascii碼一樣。

不同語言的每個字元的utf8編碼的位元組數不一樣,位元組碼也不一樣。對於英文本元,檢視它的ascii碼,很方便,將字元取出來,就是它的ascii碼。其實,對於非英文本元,取字符集編碼的方式也是這樣。這樣統稱為取ascii碼,在很多文件中也是這樣描述的。

網上很多這樣例子,介紹如何將字元和ascii碼相互轉化。但是它們都沒有提及如何轉換中文等其他非英文的字元,使用這個方法都會轉成亂碼。

使用英文轉換測試,如下所示:

// nsstring to ascii

nsstring *string = @"a";

int asciicode = [string characteratindex:0]; // 65

// ascii to nsstring

int asciicode = 65;

nsstring *string = [nsstring stringwithformat:@"%c", asciicode]; // a

再使用中文測試一下,使用[nsstring stringwithformat:@"%c", asciicode]得到的是亂碼字元,就是說根本沒識別正確。

再說解決方法之前,先了解一下stringwithformat方法中各種format。其中將ascii碼轉成字元有兩種format,分別為%c和%c。

/*%c

8-bit unsigned character (unsigned char), printed by nslog() as an ascii character, or, if not an ascii character, in the octal format \\ddd or the unicode hexadecimal format \\udddd, where d is a digit.

%c16-bit unicode character (unichar), printed by nslog() as an ascii character, or, if not an ascii character, in the octal format \\ddd or the unicode hexadecimal format \\udddd, where d is a digit.

*/使用[nsstring stringwithformat:@"%c", asciicode]就可以正常得到所要的字元。

分別以英文,中文和日文舉例。

nsstring *thestring = @"g";

unichar thechar = [thestring characteratindex:0];

nsstring *thestring1 = [nsstring stringwithformat:@"%c", thechar];

nsstring *thestring2 = [nsstring stringwithformat:@"%c", thechar];

nslog(@"thestring=%@,%d,%@,%@",thestring,thechar,thestring1,thestring2);

thestring = @"家";

thechar = [thestring characteratindex:0];

thestring1 = [nsstring stringwithformat:@"%c", thechar];

thestring2 = [nsstring stringwithformat:@"%c", thechar];

nslog(@"thestring=%@,%d,%@,%@",thestring,thechar,thestring1,thestring2);

thestring = @"カントリー";

thechar = [thestring characteratindex:2];

thestring1 = [nsstring stringwithformat:@"%c", thechar];

thestring2 = [nsstring stringwithformat:@"%c", thechar];

nslog(@"thestring=%@,%d,%@,%@",thestring,thechar,thestring1,thestring2);

2013-09-12 15:36:27.849 xyshopping[1892:18e03] thestring=g,103,g,g

2013-09-12 15:36:27.849 xyshopping[1892:18e03] thestring=家,23478,?,家

2013-09-12 15:36:27.849 xyshopping[1892:18e03] thestring=カントリー,12488,?,ト

顯示結果表明,這個方法是正確的。對於兩個位元組組成的字元,是能顯示出的。不知道其他語言會怎麼樣,沒有條件去測試。

中文轉換ascii碼

方法一 開啟命令列視窗,輸入native2ascii命令,回車,然後會有光 標在閃,切換到中文輸入 狀態,輸入要轉換的中文後回車即可。方法二首先把要轉換的檔案 如 a.txt 放到指定的目錄下 如 c 然後開啟命令列視窗 進入到c盤目錄下 輸入 native2ascii a.txt b.txt 回車...

ASCII碼 Unicode碼 轉中文

在最近工作中遇到了一些漢字編碼轉換的處理,可以通過正規表示式及轉換字元來實現轉成中文 unicode轉換示例 通常為10位編碼,通過digit引數傳入private string unicodetocnstring string unicodestring,int digit m ascii轉換示例...

輸出中文字元

輸出中文字元 要想在圖形中輸出中文字元,需要對輸出的中文字元進行編碼。使用iconv 函式,可以把一種編碼的字元,轉換為其他編碼的字元。下面介紹在圖形中輸出中文字元的方法,建立乙個新圖形 image imagecreate 400,200 設定背景,分配顏色 bgcolor imagecoloral...