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 >^ ?

Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111
dshen
  • 1
  • 1
  • 1
  • 1
    possible duplicate of [How do you convert Byte Array to Hexadecimal String, and vice versa, in C#?](http://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa-in-c) (The conversion from C# to its C++/CLI equivalent is trivial.) – Ben Voigt Jul 08 '11 at 19:52
  • Where did you get that string from? – svick Jul 08 '11 at 20:06

2 Answers2

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;
    }
};
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
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.

Joel Rondeau
  • 7,486
  • 2
  • 42
  • 54
  • While turning C# into C++/CLI is easy, it's not as simple as just tagging `^` on the end of each type. – Ben Voigt Jul 08 '11 at 19:54
  • Fixed, other than not actually compiling to check. – Joel Rondeau Jul 08 '11 at 20:04
  • `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.) – Ben Voigt Jul 08 '11 at 20:21