1

I am using Windows Forms C++/CLI and have a function that calls a Python script which returns a string representation of bytes. I would like to convert the string to an array of bytes.

For example:

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";

What this ends up printing to the text box is the decimal representation of the ascii characters:

48
57
49
53

What I am trying to get is an array with the values {0x09, 0x15, 0x3a};

1 Answer 1

2

You need a function to parse the hex string by splitting it into pairs, and then converting every pair of hex characters into a byte value.

You can see a complete example below using a console application.

Note: your hex string "09153a" represents only 3 bytes (so only zero, one, two are relevant).

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;
}

Output:

Hex: 0x09
Hex: 0x15
Hex: 0x3A
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.