Sign in to follow this  
Degorath

Assembly and C#

Recommended Posts

I have a string in Hex (very very very long) which needs to be converted into a byte array in C#. To do this takes around 2 minutes for 145KB (if error checking is disabled. If not, 5 minutes). What I would really like to do is use an assembly routine which will probably do it in a few seconds. What I would like to know is; is it possible to run an assembly routine from C# code? (The .COM file takes the string as input and returns the result) Thanks...

Share this post


Link to post
Share on other sites
I'm not sure, but you might be able to use P/Invoke.

Have a look at that!

Basically, it's a good way of including non-managed code into your C# from what I can remember.

Share this post


Link to post
Share on other sites
Look at this horror for machine code in C++/CLI:

delegate Int32 DoubleNum(Int32 x);
unsigned char pNative[] =
{
0x55, // push ebp
0x8B, 0xEC, // mov ebp,esp
0x8B, 0x45, 0x08, // mov eax,dword ptr [arg]
0x03, 0x45, 0x08, // add eax,dword ptr [arg]
0x5D, // pop ebp
0xC3 // ret
};
DoubleNum^ pDoubleNum = (DoubleNum^)
Marshal::GetDelegateForFunctionPointer(
(IntPtr)pNative, DoubleNum::typeid);
Console::WriteLine(pDoubleNum(19));

Share this post


Link to post
Share on other sites
What you would really like to do is write an efficient routine in C#.

My computer isn't top-of-the-line, but it still manages to generate 145k bytes in less than 400 milliseconds without any special optimization effort on my part...

byte [] output = new byte[input.Length / 2];
byte a = 0;
int i = 0;

foreach (char c in input)
{
byte x = hex(c);

if (i % 2 == 0) a = x;
else output[i/2] = (byte)(a * 16 + x);

++i;
}


Where hex uses a straightforward switch statement to return the 0-15 value of an 0-9A-Fa-f character.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this