winforms C++/CLI将字符串^转换为字节数组

xvw2m8pv  于 2022-11-16  发布在  其他
关注(0)|答案(1)|浏览(161)

我正在使用Windows Forms C++/CLI,并且有一个函数调用Python脚本,该脚本返回字节的字符串表示形式。我想将字符串转换为字节数组。
例如:

String^ demoString = "09153a"; // example of data returned from Python script

array<Byte>^ bytes;
    
// This is what I tried but does not give me the output I want
bytes = System::Text::Encoding::UTF8->GetBytes(demoString);

unsigned char zero = bytes[0];
unsigned char one = bytes[1];
unsigned char two = bytes[2];
unsigned char three = bytes[3];

this->richTextBox1->Text += zero + "\n";
this->richTextBox1->Text += one + "\n";
this->richTextBox1->Text += two + "\n";
this->richTextBox1->Text += three + "\n";

最后打印到文本框的是ASCII字符的十进制表示:

48
57
49
53

我尝试获取的是一个值为{0x 09,0x 15,0x 3a}的数组;

avwztpqn

avwztpqn1#

您需要一个函数来解析十六进制字符串,方法是将其拆分为若干对,然后将每对十六进制字符转换为一个字节值。
您可以在下面看到一个使用控制台应用程序的完整示例。
注意:十六进制字符串"09153a"仅代表3个字节(因此仅zeroonetwo相关)。

using namespace System;

array<Byte>^ ParseBytes(String^ str)
{
    if (str->Length % 2 != 0)
    {
        return nullptr;
    }
    int numBytes = str->Length / 2;
    array<Byte>^ bytes = gcnew array<Byte>(numBytes);
    for (int i = 0; i < numBytes; ++i)
    {
        String^ byteStr = str->Substring(i * 2, 2);
        if (!Byte::TryParse(byteStr, Globalization::NumberStyles::HexNumber, nullptr, bytes[i]))
        {
            return nullptr;
        }
    }
    return bytes;
}

int main(array<System::String ^> ^args)
{
    String^ demoString = "09153a"; // example of data returned from Python script

    array<Byte>^ bytes = ParseBytes(demoString);

    Byte zero = bytes[0];
    Byte one = bytes[1];
    Byte two = bytes[2];

    Console::WriteLine("Hex: 0x" + zero.ToString("X2"));
    Console::WriteLine("Hex: 0x" + one.ToString("X2"));
    Console::WriteLine("Hex: 0x" + two.ToString("X2"));

    return 0;
}

输出量:

Hex: 0x09
Hex: 0x15
Hex: 0x3A

相关问题