Hello everybody, I'm in need of a bit of help here. I got this C# snippet:

public static byte[] StringToByteArray(String hex)
{
    int NumberChars = hex.Length;
    byte[] bytes = new byte[NumberChars / 2];

    for (int i = 0; i < NumberChars; i += 2)
        bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
    return bytes;
}

and I need to convert it to C++. This is how far I got:

public static byte[] StringToByteArray(String^ hex)
{
    int NumberChars = hex->Length;
    byte[] bytes = new byte[NumberChars / 2];

    for (int i = 0; i < NumberChars; i += 2)
        bytes[i / 2] = Convert.ToByte(hex->Substring(i, 2), 16);
    return bytes;
}

I only changed . to -> and String to String^, so not much really. I'm working on a .NET project btw (CLR).

Yeah, the

public static byte[]

part and the

byte[] bytes = new byte[NumberChars / 2];

parts don't compile... It's C#, I need to somehow edit it to work, but I don't have any idea on what should I do more...

int NumberChars = hex->Length;

hex is the parameter I pass when using the function (StringToByteArray(String^ hex).

This may or may not be what you are trying to accomplish:

#include "stdafx.h"

using namespace System;

array<Byte^>^ StringToByteArray(String^ Str)
{
    array<Byte^>^ bytes = gcnew array<Byte^>(Str->Length);
    for(int I = 0; I < Str->Length; I++)
    {
        bytes[I] = Byte(Convert::ToByte(Str[I]));
    }
    return bytes;
}


int main(array<System::String ^> ^args)
{
    array<Byte^>^ bytes = gcnew array<Byte^>(4);
    bytes = StringToByteArray("WTF");
    for (int I = 0; I < 3; I++)
        Console::WriteLine(bytes[I]);
    Console::ReadKey();
    return 0;
}

For simple byte arrays it is not necessary to use 'Byte Pointers' on the managed heap.
triumphost code, of course is correct and works but declaring a byte array like this is more efficient.

#include "stdafx.h"

using namespace System;

array<Byte>^ StringToByteArray(String^ Str)
{
    array<Byte>^ bytes = gcnew array<Byte>(Str->Length);
    for(int I = 0; I < Str->Length; I++)
    {
        bytes[I] = Byte(Convert::ToByte(Str[I]));
    }
    return bytes;
}
int main(array<System::String ^> ^args)
{
    array<Byte>^ bytes = StringToByteArray("WTF");
    for (int I = 0; I < 3; I++)
        Console::WriteLine(bytes[I]);
    Console::ReadKey();
    return 0;
}

Also it is not necessary to create a new array (line 18 in main). The array is created in the StringToByteArray method and it's pointer return.
Milton

This article has been dead for over six months. Start a new discussion instead.