我正在使用 Windows 表單 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
我想要得到的是一個值為 {0x09, 0x15, 0x3a}; 的陣列。
uj5u.com熱心網友回復:
您需要一個函式來決議十六進制字串,將其分成對,然后將每對十六進制字符轉換為一個位元組值。
您可以在下面使用控制臺應用程式查看完整示例。
注意:您的十六進制字串"09153a"僅代表 3 個位元組(因此只有zero, one,two是相關的)。
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/522130.html
標籤:表格c -cli
