目录
????????位移运算符分为左位移运算符<<和右位移运算符>>,分别用于向左和向右执行移位运算。对于X<<N或X>>N形式的运算,含义是将X向左或向右移动N位,X的类型可以是int、uint、long、ulong、byte、sbyte、short和ushort。需要注意的是,byte、sbyte、short和ushort类型的值在进行位移操作后值的类型将自动转换成int类型。
?????????将字节序列的第一个字节向左移8位,第一个字节移8位后与第二个字节相加得到汉字编码;
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编码方式获得字节序列
int n = bytes[0] << 8; //将字节序列的第一个字节向左移8位
n += bytes[1]; //第一个字节移8位后与第二个字节相加得到汉字编码
textBox2!.Text = n.ToString(); //显示汉字编码
}
catch (Exception)
{
MessageBox.Show("请输入汉字字符!", "出现错误!");
}
}
}
}