C#使用移位運算符獲取漢字編碼的示例代碼
一、移位運算符
位移運算符分為左位移運算符<<和右位移運算符>>,分別用于向左和向右執(zhí)行移位運算。對于X<<N或X>>N形式的運算,含義是將X向左或向右移動N位,X的類型可以是int、uint、long、ulong、byte、sbyte、short和ushort。需要注意的是,byte、sbyte、short和ushort類型的值在進行位移操作后值的類型將自動轉(zhuǎn)換成int類型。
二、方法
將字節(jié)序列的第一個字節(jié)向左移8位,第一個字節(jié)移8位后與第二個字節(jié)相加得到漢字編碼;
三、示例
using System.Text; namespace _019 { public partial class Form1 : Form { private Label? label1; private TextBox? textBox1; private TextBox? textBox2; private Button? button1; public Form1() { InitializeComponent(); Load += Form1_Load; } private void Form1_Load(object? sender, EventArgs e) { // // txt_Num // textBox2 = new TextBox { Location = new Point(146, 52), Name = "txt_Num", Size = new Size(100, 21), TabIndex = 7 }; // // label1 // label1 = new Label { AutoSize = true, Location = new Point(24, 19), Name = "label1", Size = new Size(113, 12), TabIndex = 6, Text = "輸入一個漢字字符:" }; // // txt_chr // textBox1 = new TextBox { Location = new Point(146, 14), Name = "txt_chr", Size = new Size(100, 21), TabIndex = 5 }; // // btn_Get // button1 = new Button { Location = new Point(26, 50), Name = "btn_Get", Size = new Size(100, 23), TabIndex = 4, Text = "獲取漢字編碼值", UseVisualStyleBackColor = true }; button1.Click += new EventHandler(Button1_Click); // // Form1 // AutoScaleDimensions = new SizeF(6F, 12F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(269, 89); Controls.Add(textBox2); Controls.Add(label1); Controls.Add(textBox1); Controls.Add(button1); Name = "Form1"; Text = "獲取漢字編碼值"; SuspendLayout(); } /// <summary> /// GB2312并不是VS默認支持的編碼,需要安裝編碼庫。 /// </summary> private void Button1_Click(object? sender, EventArgs e) { try { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); /*char chr = textBox1!.Text.ToCharArray()[0]; *///獲取文本框中位置為1的漢字 char chr = textBox1!.Text[0]; //等效語句 char[] chars = [chr]; byte[] bytes = Encoding.GetEncoding("gb2312").GetBytes(chars: [chr]); //使用gb2312編碼方式獲得字節(jié)序列 int n = bytes[0] << 8; //將字節(jié)序列的第一個字節(jié)向左移8位 n += bytes[1]; //第一個字節(jié)移8位后與第二個字節(jié)相加得到漢字編碼 textBox2!.Text = n.ToString(); //顯示漢字編碼 } catch (Exception) { MessageBox.Show("請輸入漢字字符!", "出現(xiàn)錯誤!"); } } } }
四、生成效果
到此這篇關于C#使用移位運算符獲取漢字編碼的示例代碼的文章就介紹到這了,更多相關C#獲取漢字編碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C# Winform實現(xiàn)導入和導出Excel文件
這篇文章主要為大家詳細介紹了C# Winform實現(xiàn)導入和導出Excel文件,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-12-12C#實現(xiàn)Json轉(zhuǎn)Unicode的方法
這篇文章主要介紹了C#實現(xiàn)Json轉(zhuǎn)Unicode的方法,可實現(xiàn)輸入為帶有json格式的文本,輸出正常文本的功能,需要的朋友可以參考下2014-09-09C#實現(xiàn)DataGridView控件行列互換的方法
這篇文章主要介紹了C#實現(xiàn)DataGridView控件行列互換的方法,涉及C#中DataGridView控件元素遍歷與添加操作的相關技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-08-08