簡體   English   中英

如何將字符串轉換為字節數組

[英]How to convert a string to byte array

我有一個字符串,並希望使用C#將其轉換為十六進制值的字節數組。
例如,“Hello World!” to byte [] val = new byte [] {0x48,0x65,0x6C,0x6C,0x6F,0x20,0x57,0x6F,0x72,0x6C,0x64,0x21} ;,

我在將字符串值轉換為十六進制十進制時看到以下代碼

string input = "Hello World!";
char[] values = input.ToCharArray();
foreach (char letter in values)
{
     // Get the integral value of the character.
     int value = Convert.ToInt32(letter);
     // Convert the decimal value to a hexadecimal value in string form.
     string hexOutput = String.Format("0x{0:X}", value);                
     Console.WriteLine("Hexadecimal value of {0} is {1}", letter, hexOutput);
}

我希望這個值成為字節數組但不能這樣寫

byte[] yy = new byte[values.Length];
yy[i] = Convert.ToByte(Convert.ToInt32(hexOutput));

我嘗試從如何將字符串轉換為十六進制字節數組引用的代碼 我通過十六進制值48656C6C6F20576F726C6421,但我得到的十進制值不是十六進制。

public byte[] ToByteArray(String HexString)
{
    int NumberChars = HexString.Length;
    byte[] bytes = new byte[NumberChars / 2];
    for (int i = 0; i < NumberChars; i += 2)
    {
        bytes[i / 2] = Convert.ToByte(HexString.Substring(i, 2), 16);
    }
    return bytes;
}

我也嘗試從如何將十六進制字符串轉換為字節數組的代碼?

但是一旦我使用Convert.ToByte或byte.Parse,值就會變為十進制值。 我應該怎么做?

提前致謝

我想將0x80(即128)發送到串口,但是當我將相當於128的字符復制並粘貼到變量'input'並轉換為byte時,我得到了63(0x3F)。 所以我想我需要發送十六進制數組。 我想我的想法錯了。 請看屏幕截圖。

在此輸入圖像描述

現在,我解決這個問題來組合字節數組。

string input = "Hello World!";
byte[] header = new byte[] { 2, 48, 128 };
byte[] body = Encoding.ASCII.GetBytes(input);

十六進制與此無關,您所需的結果只不過是包含ASCII代碼的字節數組。

嘗試Encoding.ASCII.GetBytes(s)

您的要求有些奇怪:

我有一個字符串,並希望使用C#將其轉換為十六進制值的字節數組。

一個字節只是一個8位值。 您可以將其顯示為十進制(例如16)或十六進制(例如0x10)。

那么,你真正想要的是什么?

如果你真的想要獲得一個包含字節數組的十六進制表示的字符串,那么你可以這樣做:

public static string BytesAsString(byte[] bytes)
{
    string hex = BitConverter.ToString(bytes); // This puts "-" between each value.
    return hex.Replace("-","");                // So we remove "-" here.
}

看起來你正在混合轉換為數組並顯示數組數據。

當你有字節數組時,它只是字節數組,你可以用任何可能的方式表示二進制,十進制,十六進制,八進制,等等...但只有在你想要直觀地表示它們時才有效。

這是一個代碼,它手動將字符串轉換為字節數組,然后轉換為十六進制格式的字符串數組。

string s1 = "Stack Overflow :)";
byte[] bytes = new byte[s1.Length];
for (int i = 0; i < s1.Length; i++)
{
      bytes[i] = Convert.ToByte(s1[i]);
}

List<string> hexStrings = new List<string>();

foreach (byte b in bytes)
{
     hexStrings.Add(Convert.ToInt32(b).ToString("X"));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM