[C#][.NET]16進位字串(Hex string)與位元組陣列Byte[]轉換

  • 54320
  • 0
  • .NET
  • 2016-02-06

碰到的幾種密碼演算法將明文的組成及密文的輸出使用16進位字串(Hex string),但進行邏輯運算時則需要轉換為Byte[],
為了便於使用,偷偷把轉換功能寫進Extensions,因為火星任務會用到。

  • 16進位數字組成的字串轉換為Byte[]
  • Byte[]轉換為16進位數字字串
  • 取出字串右邊開始的指定數目字元

1.16進位數字組成的字串轉換為Byte[]

public static byte[] HexToByte(this string hexString)
{
    //運算後的位元組長度:16進位數字字串長/2
    byte[] byteOUT = new byte[hexString.Length / 2];
    for (int i = 0; i < hexString.Length; i = i + 2)
    {
        //每2位16進位數字轉換為一個10進位整數
        byteOUT[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16);
    }
    return byteOUT;
}

2.Byte[]轉換為16進位數字字串

public static string BToHex(this byte[] Bdata )
{
    return BitConverter.ToString(Bdata).Replace("-", "");
}


3.取出字串右邊開始的指定數目字元

//取出字串右邊開始的指定數目字元
public static string Right(this string str, int len)
{
    return str.Substring(str.Length - len, len);
}
//取出字串右邊開始的指定數目字元(跳過幾個字元)
public static string Right(this string str, int len, int skiplen)
{
    return str.Substring(str.Length - len - skiplen, len);
}

準備測試劇本,這邊假設

1.把字串Hello World!轉換為16進位字串。

2.轉換成功後,再利用16進位字串轉換回來字串Hello World!

3.取字串中的World。

Hello World! 16進位字串對照

H e l l o   W o r l d !
48 65 6C 6C 6F 20 57 6F 72 6C 64 21

//使用ASCII字元集將位元組轉換為字元組(字串)
Encoding Enc = Encoding.ASCII;

//字串[Hello World!]
string MyFirstFunction = "Hello World!";
//將字串[Hello World!]轉換為16進位字串(Hex string)
string hexValues = Enc.GetBytes(MyFirstFunction).BToHex();
Console.WriteLine("Method:string to Hexstring");
Console.WriteLine("{0} = {1}", MyFirstFunction, hexValues);
Console.WriteLine("");

//[Hello World!]的16進位字串(Hex string)轉換為位元組陣列
byte[] bdata  = hexValues.HexToByte();
Console.WriteLine("Method:Hexstring to string");
Console.WriteLine("{0} = {1}", hexValues, Enc.GetString(bdata));
Console.WriteLine("");

//取出World
Console.WriteLine("Method:Right");
Console.WriteLine("{0} = {1}", MyFirstFunction, MyFirstFunction.Right(5,1));

測試成功

補基礎,筆記下來。其實16進位制比英文字母(拉丁字母)好表達,哈! 看火星任務(Mission to Mars)學到的,利用360度方位表達Hex string進行最近5000萬公里遠距溝通。

 

參考:

如何:在十六進位字串和數字類型間轉換 (C# 程式設計手冊)

VB.NET String.Right

Convert.ToByte()