现在的位置: 首页 > 综合 > 正文

字符与16进制的转换(一)

2018年08月05日 ⁄ 综合 ⁄ 共 4049字 ⁄ 字号 评论关闭

This original article is from http://www.codeproject.com/KB/recipes/hexencoding.aspx

Introduction

While the .NET framework provides methods to convert a byte array into a Hexadecimal string ( byte.ToString(�X�) ), it is not so easy to convert a hexadecimal string back into a byte array. Such a function is useful when you need to backup data from your application on paper, such as an encryption key, and later, convert it back into data after the user types it in.

The HexEncoding class provided here, contains functions which allow for the conversion of a string in hexadecimal format into a byte array, and back. It also contains functions which lets you check the formatting of the string before conversion, and how many bytes a given string will produce.

Background

In a hexadecimal string, one byte is represented two hexadecimal characters. A hexadecimal character has a value of (A-F, 0-9).

e.g. string �01FFA0� is equivalent to byte[] { 1, 255, 160 }

Using the code

HexEncoding is the name of the class I created with static functions for hexadecimal string conversion.

Here�s a sample of how it is used, when the Convert button is clicked like on the screenshot:

Collapse | Copy Code
private void button1_Click(object sender, System.EventArgs e)
{
    string hexString = txtHex.Text;
    int discarded;
    txtByteCount.Text = ((int)HexEncoding.GetByteCount(hexString)).ToString();
    txtLength.Text = hexString.Length.ToString();
    byte[] byteArray = HexEncoding.GetBytes(hexString, out discarded);
    txtDiscard.Text = discarded.ToString();
    string temp = "";
    for (int i=0; i<byteArray.Length; i++)
    {
        temp += byteArray[i].ToString("D3") + " ";
    }
    txtByte.Text = temp;
    txtHex2.Text = HexEncoding.ToString(byteArray);
}

HexEncoding.GetByteCount(string hexString) returns the number of bytes that will be generated from the hexString.

HexEncoding.GetBytes(string hexString, out int discarded) returns the byte array converted from the hexString, and the second parameter returns the number of non-hexadecimal characters that were ignored in the string. This includes dashes, whitespace, and letters after �F�.

HexEncoding.ToString(byte[]) returns the newly converted byte array back into string form. Notice the �-� characters are now missing.

The key function provided by the framework to convert a hexadecimal string to a single byte is this:

Collapse | Copy Code
// byte newByte = byte.Parse(hex, System.Globalization.NumberStyles.HexNumber);

where �hex� is of the form �1A�, �00�, �FF�, etc.

Thanks to Polux on the .NET 247 newsgroups who posted the int.Parse(...) answer to another hexadecimal question.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

neilck

 

 

 

Folks, be carefull when using ASCIIEncoding for such conversion from byte array. As you may know, byte array can contain values that goes beyond 128. What we usually forget is that ASCIIEncoding works with 7 bits only. When converting, the values will get mixed up.

See the sample below:

byte[] byteArray = {192, 65, 66, 67}; 
string str1 = System.Text.Encoding.ASCII.GetString(byteArray); 
string str2 = System.Text.Encoding.Unicode.GetString(byteArray); 
string str3 = System.Text.Encoding.UTF8.GetString(byteArray); 
string str4 = System.Text.Encoding.Default.GetString(byteArray); 
 
byte[] res1 = System.Text.Encoding.ASCII.GetBytes(str1);//returns {63, 65, 66, 67} 
byte[] res2 = System.Text.Encoding.Unicode.GetBytes(str2);//returns  {192, 65, 66, 67} 
byte[] res3 = System.Text.Encoding.UTF8.GetBytes(str3);//returns {239, 191, 189, 65, 66, 67} 
byte[] res4 = System.Text.Encoding.Default.GetBytes(str4);//returns {192, 65, 66, 67}; 
 

So I would consider using unicode for this kind of conversion.

 

Basically, I need to read decimal representations of byte characters in, and save them in a byte array.  Each line in the file I'm reading will be an array of bytes once I'm done.  Here's an example of one line of data:

Code Block

string temp = "255 255 255 0 243 8 50";

As you can see, there are 7 bytes represented in this line, when i am finished, I want a byte[] with the 7 bytes in it.

Here's what I'm thinking codewise:

Code Block

string[] byteStrings = temp.Split(" ");

byte[] byteOut = new byte[byteStrings.Length];

for(int i = 0; i < byteStrings.Length; i++)

{

    byteOut[i] = Convert.ToByte(byteStrings[i]);

}

Does this look like it will work?  I am going to test it now and I will post a reply if it works or not.

抱歉!评论已关闭.