using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public string StringToHex(string str)
{
//str = str.Trim();
//int i;
/* char[] values = str.ToCharArray();
foreach (char aa in values)
{
aa = aa - 30;
}
*/
int i;
byte[] ByteFoo = System.Text.Encoding.Default.GetBytes(str);//将输入的字符转成16进制
string TempStr = "";
byte[] aa = new byte[ByteFoo.Length/2];
byte[] bb = new byte[ByteFoo.Length/2];
byte[] cc = new byte[ByteFoo.Length/2];
byte[] dd = new byte[ByteFoo.Length/2];
for (i=0;i<ByteFoo.Length/2;i++)
{
aa[i] = (byte)(ByteFoo[2 * i] << 4);//将奇数字节转成BCD码 31---》1
bb[i] = (byte)(ByteFoo[2 * i + 1] << 4);
dd[i] = (byte)(bb[i] >> 4);// 将偶数字节转成BCD码
cc[i] = (byte)(aa[i] | dd[i]);//合并
}
foreach (byte b in cc)
{
//(b << 4);
TempStr += b.ToString("X"); //X表示十六进制显示
}
return TempStr;
}
/// <summary>
///将2n字符压缩成n个字符
///str 5678
///ByteFoo 35 36 37 38
///aa 50 70
///bb 60 80
///dd 06 08
///cc 56 78
/// </summary>
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string str;
string bb;
str = textBox1.Text;
//bb = ConvertToHex(str);
bb = StringToHex(str);
textBox3.Text = bb;
}
}
}