0

I'm trying to send a string of hex values through udp,

11 22 33 44 37 4D 58 33 38 4C 30 39 47 35 35 34 31 35 31 04 D7 52 FF 0F 03 43 2D AA

using UdpClient in C++.

What's the best way to convert string^ to  array< Byte >^ ?

2

2 Answers 2

1

This works for me, although I haven't tested the error-detection all that well.

ref class Blob
{
    static short* lut;
    static Blob()
    {
        lut = new short['f']();
        for( char c = 0; c < 10; c++ ) lut['0'+c] = 1+c;
        for( char c = 0; c < 6; c++ ) lut['a'+c] = lut['A'+c] = 11+c;
    }
public:
    static bool TryParse(System::String^ s, array<System::Byte>^% arr)
    {
        array<System::Byte>^ results = gcnew array<System::Byte>(s->Length/2);
        int index = 0;
        int accum = 0;
        bool accumReady = false;
        for each (System::Char c in s) {
            if (c == ' ') {
                if (accumReady) {
                    if (accum & ~0xFF) return false;
                    results[index++] = accum;
                    accum = 0;
                }
                accumReady = false;
                continue;
            }
            accum <<= 4;
            accum |= (c <= 'f')? lut[c]-1: -1;
            accumReady = true;
        }
        if (accumReady) {
            if (accum & ~0x00FF) return false;
            results[index++] = accum;
        }
        arr = gcnew array<System::Byte>(index);
        System::Array::Copy(results, arr, index);
        return true;
    }
};
Sign up to request clarification or add additional context in comments.

Comments

0

If you're trying to send that as ascii bytes, then you probably want System::Text::Encoding::ASCII::GetBytes(String^).

If you want to convert the string to a bunch of bytes first (so first byte sent is 0x11), you'll want to split your string based on whitespace, call Convert::ToByte(String^, 16) on each, and put them into an array to send.

3 Comments

While turning C# into C++/CLI is easy, it's not as simple as just tagging ^ on the end of each type.
Fixed, other than not actually compiling to check.
System::String has a capital S. Lowercase string is a C# keyword, and also a native C++ type std::string, but never means .NET String. (Yeah, I know the question got it wrong too.)

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.